如何制作旋转鼠标的东西?

时间:2018-01-28 07:44:01

标签: javascript html html5-canvas mouseevent mouse

我正在尝试解决一段时间困扰我的问题,有人可以向我解释如何制作*红色矩形面/瞄准我的鼠标并向我解释它是如何工作的它会很棒!! !

以下是 Fiddle



var canvas = document.getElementById('canvas');

var context = canvas.getContext('2d');

var player = {
  x: 200,
  y: 200,
}

drawPlayer = function(something) {
  context.beginPath();
  context.fillStyle = "blue";
  context.arc(something.x, something.y, 30, 0, 2 * Math.PI);
  context.fill();

  context.fillStyle = "red";
  context.fillRect(something.x, something.y - 10, 50, 20);
  context.restore();
}

update = function() {
  context.clearRect(0, 0, 500, 500)
  drawPlayer(player);
}

setInterval(update, 20);

<canvas id="canvas" style="outline: 1px solid #ccc" width="500" height="500"></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

使用context.translate将坐标转换为播放器的中心,然后context.rotate旋转矩形。

要查找鼠标位置与播放器中心之间的角度,您可以使用Math.atan2功能。

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var player = {
    x: 200,
    y: 200,
}

drawPlayer = function(something, angle) {
    context.clearRect(0, 0, 500, 500);
    context.beginPath();
    context.fillStyle = "blue";
    context.arc(something.x, something.y, 30, 0, 2 * Math.PI);
    context.fill();

    // save the untranslated context
    context.save();
    context.beginPath();
    // move the rotation point to the center of the player
    context.translate(something.x, something.y);
    context.rotate(angle);

    context.fillStyle = "red";
    // note that coordinates are translated, 
    // so 0 is player.x and -10 is player.y - 10
    context.fillRect(0, - 10, 50, 20);
    // restore the context to its untranslated state
    context.restore();
}

drawPlayer(player, 0);

document.onmousemove = function(e) { 
    var angle = Math.atan2(e.pageY - player.y, e.pageX - player.x)
    drawPlayer(player, angle);
}
<canvas id="canvas" style="outline: 1px solid #ccc" width="500" height="500"></canvas>