拖动;在画布图像上放下图像

时间:2013-10-04 07:54:35

标签: html5 drag-and-drop html5-canvas

我想拖动&删除图像上方的文字。为此,我使用帆布。我正在使用此代码

<img id="scream" src="http://127.0.0.1/demo/images.jpg" alt="The Scream" style="display:none;" width="220" height="277"><p>Canvas:</p>
  <canvas id="canvas" width="300" height="300" style="border:1px solid #d3d3d3;">
       Your browser does not support the HTML5 canvas tag.</canvas>


var c=document.getElementById("canvas");
var ctx1=c.getContext("2d");
var img=document.getElementById("scream");
ctx1.drawImage(img,10,10);

var canvas;
var ctx;
var x = 75;
var y = 50;
var dx = 5;
var dy = 3;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false,
    text = "Hey there im moving!",
    textLength = (text.length * 14)/2;

function rect(x,y,w,h) {
 ctx.font = "14px Arial";
 ctx.strokeText("Hey there im a moving!!", x, y);
}

function clear() {
 ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

function init() {
 canvas = document.getElementById("canvas");
 ctx = canvas.getContext("2d");
 return setInterval(draw, 10);
}

function draw() {
 clear();
 ctx.fillStyle = "#FAF7F8";
 ctx.fillStyle = "#444444";
 rect(x - 15, y + 15, textLength, 30);
}

function myMove(e){
 if (dragok){
  x = e.pageX - canvas.offsetLeft;
  y = e.pageY - canvas.offsetTop;
 }
}

function myDown(e){
 if (e.pageX < x + textLength + canvas.offsetLeft && e.pageX > x - textLength + canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
 e.pageY > y -15 + canvas.offsetTop){
  x = e.pageX - canvas.offsetLeft;
  y = e.pageY - canvas.offsetTop;
  dragok = true;
  canvas.onmousemove = myMove;
 }
}

function myUp(){
 dragok = false;
 canvas.onmousemove = null;
}

init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;

我要么能够显示图像,要么拖动图像。放下文字,但我想要两个,请帮助我,我错了。您可以在此处查看: - http://jsfiddle.net/FWdSv/11/

1 个答案:

答案 0 :(得分:2)

当您清除画布时,您还要清除图像。

因此,简单的解决方法是在绘图功能中重绘图像:

function draw() {
 clear();
 ctx.drawImage(img,0,0);
 ctx.fillStyle = "#FAF7F8";
 ctx.fillStyle = "#444444";
 rect(x - 15, y + 15, textLength, 30);
}

可替换地:

您可以在画布下方显示图像,以便在清除画布时不受影响。

相关问题