你可以得到这样的鼠标和肩膀之间的角度:
var dx = mouseX - shoulderX;
var dy = mouseY - shoulderY;
var angle=Math.atan2(dy,dx);
你可以从肩部向获得武器端点鼠标就像这样:
var endX = shoulderX + armlength * Math.cos(angle);
var endY = shoulderY + armlength * Math.sin(angle);
这里的电子商务xample代码和演示:
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>
你鼠标相对于上次鼠标位置的移动或相对于画布上的固定位置想?另外,如果鼠标同时向右移动,你想要什么? – markE 2014-11-01 16:12:11
@markE如果鼠标在同一时间向上和向右移动,手臂会逆时针旋转,不确定相对于固定位置的含义 – user3558118 2014-11-01 16:17:36