简体   繁体   English

通过JavaScript使用Canvas,如何使圆移动到单击它的位置?

[英]Using Canvas via JavaScript, How Can I make a circle move to where I click it?

I have a project here that I'm working on so that using canvas I can try where the user is clicking. 我在这里正在处理一个项目,以便可以使用画布尝试用户单击的位置。 I am trying to draw a 10px circle - just small enough to see where the user has clicked on the canvas and as well as move to where the user has click and follow the cursor. 我正在尝试绘制一个10像素的圆圈-足够小,以查看用户在画布上单击的位置以及移至用户单击并跟随光标的位置。 Below is my code but the circle is not showing for some reason. 以下是我的代码,但由于某些原因未显示圆圈。 I'm still somewhat new to canvas and JavaScript and any help is appreciated. 我对canvas和JavaScript还是有些陌生,可以提供任何帮助。

 var cn = document.getElementById("main"); var c = cn.getContext("2d"); var mouse = {x:150, y:0}; window.addEventListener('mousedown', mHandler); function mHandler(event) { //mouse.x = event.clientX; //mouse.y = event.clientY; mouse.x = event.pageX; mouse.y = event.pageY; }; function main() { c.clearRect(0, 0, cn.width, cn.height); ctx.beginPath(); ctx.arc(0, 0, 0, 0, 2 * Math.PI); ctx.stroke(); c.fillRect(mouse.x, mouse.y, 50, 50); } setInterval(main, 1000 / 60); 
 <p>Click on the Canvas!</p> <canvas id="main" height="300" width="300" style="border: 1px solid black"></canvas> 

You're drawing a circle of radius 0 at 0 x 0. 您在0 x 0处绘制半径为0的圆。

I'm using ctx.save() / ctx.translate() / ctx.restore() here to mutate the transformation matrix of the context first, so we're still drawing at 0x0 in that matrix. 我在这里使用ctx.save() / ctx.translate() / ctx.restore()更改上下文的转换矩阵,因此我们仍在该矩阵中绘制0x0。 (It makes additional transformations a little easier to wrap one's head around.) (这使得附加的转换稍微容易一些。)

(You could also just ctx.arc(mouse.x, mouse.y, 50, ...) .) (您也可以只是ctx.arc(mouse.x, mouse.y, 50, ...) 。)

In addition, you want to use offsetX / offsetY so you get the mouse coordinate relative to the canvas, not the page. 另外,您想使用offsetX / offsetY以便获得相对于画布而不是页面的鼠标坐标。

 var cn = document.getElementById("main"); var ctx = cn.getContext("2d"); var mouse = { x: 150, y: 0 }; window.addEventListener("mousedown", mHandler); function mHandler(event) { mouse.x = event.offsetX; mouse.y = event.offsetY; } function main() { ctx.clearRect(0, 0, cn.width, cn.height); ctx.save(); ctx.translate(mouse.x, mouse.y); ctx.beginPath(); ctx.arc(0, 0, 50, 0, 2 * Math.PI); ctx.stroke(); ctx.restore(); ctx.fillRect(mouse.x, mouse.y, 5, 5); } setInterval(main, 1000 / 60); 
 <p>Click on the Canvas!</p> <canvas id="main" height="300" width="300" style="border: 1px solid black"></canvas> 

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

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