你可以得到這樣的鼠標和肩膀之間的角度:
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