簡體   English   中英

HTMl5向鼠標坐標旋轉精靈

[英]HTMl5 rotating sprite towards mouse coords

我試圖將精靈朝鼠標位置旋轉,但是我只是想不出正確的方法來計算角度。 該船始終面臨着錯誤的方向。

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> 

看起來您只需要對算法進行求逆。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM