###前提・実現したいこと
ap.pngは飛行機の画像です。
実現したい機能は
1)飛行機がマウスを追従
→実現済み
2)飛行機の頭がマウスの方向を向く
→例えばマウスを右回りにしたら飛行機も右回り、マウスを左回りにしたら飛行機も左回りになるようにしたい。
canvasにこだわりませんので、上記2)が簡単に実現できるアドバイスいただければ幸いです。
お導きのほど、宜しくお願いします。
###該当のソースコード
lang
1<canvas id="canvas-container" width="100%" height="100%"></canvas>
lang
1html, body { 2 width: 100%; 3 height: 100%; 4} 5* { 6 margin: 0; 7 padding: 0; 8} 9#canvas-container { 10 width: 100%; 11 height: 100%; 12 background: #eee; 13}
lang
1 2var theta = 10; 3 4window.requestAnimFrame = (function(){ 5 return window.requestAnimationFrame || 6 window.webkitRequestAnimationFrame || 7 window.mozRequestAnimationFrame || 8 window.oRequestAnimationFrame || 9 window.msRequestAnimationFrame || 10 function(callback){ 11 window.setTimeout(callback, 1000 / 60); 12 }; 13})(); 14 15 16window.onload = function() { 17 // Canvas未サポートは実行しない 18 if (!window.HTMLCanvasElement) return; 19 20 var canvas = document.querySelector('#canvas-container'); 21 var ctx = canvas.getContext('2d'); 22 var queue = null; 23 24 var img = new Image(); //新規画像オブジェクト 25 img.src = "./ap.png"; //読み込みたい画像のパス 26 27 // Canvasサイズを100% 28 29 window.addEventListener("resize", function() { 30 clearTimeout( queue ); 31 queue = setTimeout(function() { 32 setCanvasSize(); 33 }, 300 ); 34 }, false ); 35 36 var setCanvasSize = function() { 37 canvas.width = document.documentElement.clientWidth; 38 canvas.height = document.documentElement.clientHeight; 39 }; 40 setCanvasSize(); 41 42 43 var clickPoint = { 44 x: 0, 45 y: 0 46 }; 47 48 var Particle = function(scale, color, speed) { 49 this.scale = scale; //大きさ 50 this.color = color; //色 51 this.speed = speed; //速度 52 this.position = { // 位置 53 x: 0, 54 y: 0 55 }; 56 }; 57 58 Particle.prototype.draw = function() { 59 ctx.beginPath(); 60 ctx.drawImage(img, this.position.x-25, this.position.y-25, 50, 50) 61 ctx.fillStyle = this.color; 62 ctx.fill(); 63 }; 64 65 Particle.prototype.update = function() { 66 this.position.x += (clickPoint.x - this.position.x) / this.speed; 67 this.position.y += (clickPoint.y - this.position.y) / this.speed; 68 69 this.draw(); 70 }; 71 72 var particle = new Particle(0, '#D0A000', 5); 73 74 var loop = function() { 75 requestAnimFrame(loop); 76 // 描画をクリアー 77 ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height); 78 79 particle.update(); 80 }; 81 loop(); 82 83 var rect = canvas.getBoundingClientRect(); 84 85 canvas.addEventListener('mousemove', function(e) { 86 var mouseX = e.clientX - rect.left; 87 var mouseY = e.clientY - rect.top; 88 89 clickPoint.x = mouseX; 90 clickPoint.y = mouseY; 91 92 }, false); 93};
回答1件
あなたの回答
tips
プレビュー