HTMl5旋转精灵朝向鼠标坐标

时间:2016-05-20 08:43:27

标签: javascript html5 rotation

我正在尝试将精灵旋转到鼠标位置,但我只是想弄清楚计算角度的正确方法。船总是面向错误的方向。

angle = Math.atan2( ship_coords[0] - e.clientX ,ship_coords[1] -  e.clientY  );

请参阅以下示例:

var c=document.getElementById("myCanvas");
	var ctx=c.getContext("2d");
	
	var ship = new Image();
	var ship_coords = [c.width/2, c.height/2]
	
	ship.onload = function(){
		window.requestAnimationFrame(draw);
	}
	
	ship.src = "http://pixeljoint.com/files/icons/spaceship.png";
	
	var TO_RADIANS = Math.PI/180; 
	var angle = 0;
	
	c.addEventListener("mousemove", function(e){
		angle = Math.atan2( ship_coords[0] - e.clientX ,ship_coords[1] -  e.clientY  );
	})
	

	function draw(){
		ctx.clearRect( 0,0,c.width,c.height );
		ctx.save(); 
		ctx.translate( ship_coords[0], ship_coords[1] ); //// align to center ///
		ctx.rotate( angle );
		ctx.drawImage( ship, -(ship.width/2), -(ship.height/2) ); //// set center of the image ////
		ctx.restore();
		window.requestAnimationFrame( draw );
	}
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
	  #myCanvas {
		border: 1px solid #000;
		width: 578px;
		height: 200px;
	  }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

看起来你只需要反转算术。