简体   繁体   English

HTMl5向鼠标坐标旋转精灵

[英]HTMl5 rotating sprite towards mouse coords

I'm trying to rotate a sprite towards mouse position, but I just fail at figuring out the proper way to to calculate the angle. 我试图将精灵朝鼠标位置旋转,但是我只是想不出正确的方法来计算角度。 The ship is always facing wrong direction. 该船始终面临着错误的方向。

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

Please see the below example: 请参见以下示例:

 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> 

看起来您只需要对算法进行求逆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM