简体   繁体   English

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

[英]How to display image in canvas at the position of my mouse cursor?

How can I display image in a canvas at the position of my mouse cursor so that it can move around with my mouse movement. 如何在canvas上的鼠标指针position显示图像,以便图像可以随mouse移动而移动。

Here is the code but it does not work: 这是代码,但是不起作用:

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

If I use the code that is currently out it will work. 如果我使用当前输出的代码,它将可以正常工作。 However that is just a still image. 但是,那只是静止图像。 I want to be able to move the image around with my mouse cursor. 我希望能够用鼠标光标移动图像。 Thanks. 谢谢。

Remove the square bracket here and it works 删除此处的方括号即可

window.pageYOffset)], 224, 320);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM