用鼠标旋转固定大小的线条

Rotate line with fixed size by mouse

本文关键字:鼠标 旋转      更新时间:2023-11-24

我正试图在台球游戏中创建类似球杆的东西,需要用鼠标旋转固定大小的线。

我希望鼠标位置后面的那条线是固定的,例如100个像素。

演示:http://jsfiddle.net/DAEpy/1/

我尝试使用rotate()函数来执行此操作,但它会旋转所有画布。

所以,我的线有一个固定的末端和固定的大小(可能是100像素),它将跟随鼠标。

谢谢。

只需确定直线起点和鼠标位置之间的角度:

var dx = mouse.x - line.x1,
    dy = mouse.y - line.y1,
    angle = Math.atan2(dy, dx);

然后使用100像素半径渲染线条:

line.x2 = line.x1 + 100 * Math.cos(angle);
line.y2 = line.y1 + 100 * Math.sin(angle);

Demo

var ctx = document.querySelector("canvas").getContext("2d"),
    line = {
      x1: 150, y1: 70,
      x2: 0, y2: 0
    },
    length = 100;
window.onmousemove = function(e) {
  //get correct mouse pos
  var rect = ctx.canvas.getBoundingClientRect(),
      x = e.clientX - rect.left,
      y = e.clientY - rect.top;
  // calc line angle
  var dx = x - line.x1,
      dy = y - line.y1,
      angle = Math.atan2(dy, dx);
  //Then render the line using 100 pixel radius:
  line.x2 = line.x1 + length * Math.cos(angle);
  line.y2 = line.y1 + length * Math.sin(angle);
 
  // render
  ctx.clearRect(0, 0, 300, 150);
  ctx.beginPath();
  ctx.moveTo(line.x1, line.y1);
  ctx.lineTo(line.x2, line.y2);
  ctx.stroke()
  
}
<canvas></canvas>