如何在我的鼠标光标位置的画布上显示图像?

时间:2015-09-08 23:30:06

标签: javascript html canvas

如何在canvas鼠标光标的position处显示图像,以便它可以随mouse移动一起移动。

以下是代码,但不起作用:



var canvas = document.getElementById("mycanvas");
context = canvas.getContext("2d");
canvas.addEventListener("mousemove", mouseMoved);
context.fillText("Put mouse here", 10, 10);

function mouseMoved(e) {
    context.clearRect(0, 0, canvas.width, canvas.height);
    var imageObj = new Image();

    imageObj.src = "avatar.png";
    imageObj.onload = function() {
        context.drawImage(imageObj, e.clientX - (canvas.offsetLeft - window.pageXOffset), e.clientY - (canvas.offsetTop - window.pageYOffset)], 224, 320);
};

// the following code that displays a still image works.
/*var imageObj = new Image();

imageObj.src = "avatar.png";
imageObj.onload = function() {
context.drawImage(imageObj, 225, 100, 224, 320);
};*/
}

text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
<canvas id="mycanvas" width="800" height="450", position: relative></canvas>
text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
text<br/>
&#13;
&#13;
&#13;

如果我使用当前输出的代码,它将起作用。然而,这只是一个静止图像。我希望能够用鼠标光标移动图像。感谢。

1 个答案:

答案 0 :(得分:0)

在这里取下方括号,它可以正常工作

window.pageYOffset)], 224, 320);

http://jsfiddle.net/sjmcpherso/dnt12psm/