简体   繁体   中英

Gather mouse position on canvas using Javascript

Is there a simple way to gather the mouse pointer on the screen without using jquery to rotate something. I have a figure on screen with arms and want them to rotate in the direction of the muse pointer. For Example how would I do something like shown below

if (mosue_moved_up) {
digit = 1;
} else if (mouse_moved_down) {
digit = 2;
} else if (mouse_moved_right) {
digit =3;
} else if (mouse_moved_left) {
digit = 4;
}

You can get the angle between mouse and shoulder like this:

var dx = mouseX - shoulderX;
var dy = mouseY - shoulderY;
var angle=Math.atan2(dy,dx);

And you can get the arms endpoint from the shoulder towards the mouse like this:

var endX = shoulderX + armlength * Math.cos(angle);
var endY = shoulderY + armlength * Math.sin(angle);

Here's example code and a Demo:

 var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; var BB=canvas.getBoundingClientRect(); var offsetX=BB.left; var offsetY=BB.top; ctx.lineCap='round'; ctx.fillStyle='blue'; ctx.strokeStyle='green'; ctx.lineWidth=8; var PI=Math.PI; var cx=150; var cy=150; var armlength=65; canvas.onmousemove=handleMousemove; draw(0,0); function handleMousemove(e){ e.preventDefault(); e.stopPropagation(); var mouseX=e.clientX-offsetX; var mouseY=e.clientY-offsetY; draw(mouseX,mouseY); } function draw(mouseX,mouseY){ var dx=mouseX-cx; var dy=mouseY-cy; var angle=Math.atan2(dy,dx); var x=cx+armlength*Math.cos(angle); var y=cy+armlength*Math.sin(angle); ctx.clearRect(0,0,cw,ch); ctx.fillRect(cx-15,cy-10,30,100); ctx.beginPath(); ctx.moveTo(cx,cy); ctx.lineTo(x,y); ctx.strokeStyle='green'; ctx.stroke(); } 
 body{ background-color: ivory; } canvas{border:1px solid red;} 
 <h4>"Arm" will move as the mouse moves.</h4> <canvas id="canvas" width=300 height=300></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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