オブジェクトを円運動させます。円運動は三角関数(サイン/コサイン)を利用して表現することができます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>円運動</title> <style> *{ margin: 0px; padding: 0px; } #canvas { background-color: #000; } </style> <head> <body> <canvas id="canvas" width="500" height="500"> ブラウザが対応しておりません。 </canvas> <script> window.addEventListener('load', draw, false); function draw(){ var r = 200; //半径 var x,y; //オブジェクトの座標 var degree = 0; //角度 var radian; //ラジアン var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); function loop(){ degree += 1; radian = degree * Math.PI/180; //度をラジアンに変換 x = r * Math.cos(radian) + canvas.width/2; y = r * Math.sin(radian) + canvas.height/2; context.clearRect(0, 0, canvas.width, canvas.height); context.beginPath(); context.fillStyle = 'green'; context.arc(x, y, 10, 0, Math.PI*2); context.fill(); context.closePath(); requestAnimationFrame(loop); } loop() } </script> </body> </html> |
31〜46行目 loop()
loop関数を繰り返すたびに角度(degree)を1度増やしていきます。この角度の大きさが円運動する際の速さになっています。
35・36行目
円運動するオブジェクトの座標は、コサイン(cos()メソッド)とサイン(sin()メソッド)を利用して求めることができます。
その際に度をラジアンに変換する必要あります(33行目)。1度はπ/180ラジアンです。canvas.width / 2とcanvas.height / 2はcanvasの中心点の座標です。
関連ページ
requestAnimationFrameでアニメーションをおこなう
角度を指定してオブジェクトを動かす[cos/sin][ベクトル]
スポンサーリンク