波のアニメーションを表現してみます。
前回は「静止している正弦波」(下記関連ページ参照)を表現してみましたが、今回はその「静止している正弦波」をアニメーションし、実際に波として動いているような挙動を表現してみます。
関連ページ
波を表現する[正弦波][角速度ω][sin][Math.PI]
イメージとしては、下記のイラストのように「静止している正弦波」の各点を少しづつずらして描写しています。つまり各点において単振動させている感じです。
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 56 57 58 59 60 61 62 |
<!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="600" height="500"> ブラウザが対応しておりません。 </canvas> <script> window.addEventListener('load', draw, false); function draw(){ var r = 100; //振幅 var T = 600; // 周期 var degree = 0; //角度 var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); function loop() { //繰り返される関数 ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.strokeStyle = 'green'; ctx.lineWidth = 2; drawWave(degree); ctx.stroke(); degree += 3; //3度づつ増やしていく requestAnimationFrame(loop); } loop(); function drawWave(degree) { ctx.moveTo(0, -r*Math.sin((2*Math.PI/T)*degree)+(canvas.height/2)); //始点 for (var x=1; x <= canvas.width; x+= 1) { var y =-r*Math.sin((2*Math.PI/T)*(degree+x)); ctx.lineTo(x, y+(canvas.height/2)); } } } </script> </body> </html> |
42行目
角度を増やしているのは、イラストでは↑↓の矢印の部分です。各点における単振動のy軸の位置を変化させています。
下記のデモ画面2では波の下の部分を、半透明の緑色で塗りつぶしています(42〜47行目を追加)。
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
<!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="600" height="500"> ブラウザが対応しておりません。 </canvas> <script> window.addEventListener('load', draw, false); function draw(){ var r = 100; //振幅 var T = 600; // 周期 var degree = 0; //角度 var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); function loop() { //繰り返される関数 ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.strokeStyle = 'green'; ctx.lineWidth = 2; drawWave(degree); ctx.stroke(); ctx.fillStyle = 'green'; ctx.globalAlpha = 0.5; ctx.lineTo(canvas.width, canvas.height); //パスをcanvasの右下まで ctx.lineTo(0, canvas.height); //パスをcanvasの左下まで ctx.closePath() //パスを閉じる ctx.fill(); //塗りつぶす degree += 3; //3度づつ増やしていく requestAnimationFrame(loop); } loop(); function drawWave(degree) { ctx.moveTo(0, -r*Math.sin((2*Math.PI/T)*degree)+(canvas.height/2)); //始点 for (var x=1; x <= canvas.width; x+= 1) { var y =-r*Math.sin((2*Math.PI/T)*(degree+x)); ctx.lineTo(x, y+(canvas.height/2)); } } } </script> </body> </html> |
参照ページ
『JavaScriptゲームプログラミング 知っておきたい数学と物理の基本』
著者: 田中 賢一郎