1

我想将文本拖放到图像上方。为此,我正在使用画布。我正在使用此代码

<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/

4

1 回答 1

2

当你清理画布时,你也在清理你的图像。

因此,简单的解决方法是在您的绘图函数中重绘图像:

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

或者:

您可以在画布下方显示图像,这样当您清除画布时它不会受到影响。

于 2013-10-06T16:45:50.550 回答