使用Javascript在画布上收集鼠标位置

时间:2014-11-01 15:59:17

标签: javascript canvas rotation

是否有一种简单的方法可以在屏幕上收集鼠标指针,而无需使用jquery来旋转某些内容。我有一个带有手臂的屏幕上的数字,并希望它们在缪斯指针的方向上旋转。例如,我将如何执行如下所示的操作

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;
}

1 个答案:

答案 0 :(得分:1)

您可以像这样获得鼠标和肩膀之间的角度:

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);

以下是示例代码和演示:

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>