How do I make something Rotate towards mouse?

痴心易碎 提交于 2019-12-13 17:31:07

问题


I am trying to solve a question which has been bugging me for a while, can someone explain to me how to make the *red rectangle face/aim towards my mouse and explain to me how it works it would be awesome!!!

Here is the 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>

回答1:


Use context.translate to translate coordinates to the center of your player and then context.rotate to rotate the rectangle.

To find the angle between the mouse position and the center of the player you can use Math.atan2 function.

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>


来源:https://stackoverflow.com/questions/48484237/how-do-i-make-something-rotate-towards-mouse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!