Created
December 9, 2017 14:54
-
-
Save arailly/ea81cc4ec40481c047dfe1deb3db6bfe to your computer and use it in GitHub Desktop.
movie of doppler effect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const WIDTH = 400; | |
const HEIGHT = 300; | |
const MAX_RADIUS = HEIGHT / 2; | |
// canvas要素を作る | |
const canvas = document.createElement('canvas'); | |
canvas.width = WIDTH; | |
canvas.height = HEIGHT; | |
// コンテキストを取得 | |
const context = canvas.getContext('2d'); | |
// body要素に追加 | |
document.body.appendChild(canvas); | |
//波紋クラス | |
class Ripple { | |
constructor(x, y, radius) { | |
this.x = x; | |
this.start_x = x; | |
this.y = y; | |
this.radius = radius; | |
this.finishFlag = 0; | |
this.velocity = 0.2; // この速度で膨張 | |
} | |
// 更新メソッド | |
// これが呼ばれるとオブジェクトの状態を更新 | |
update(duck_x) { | |
if(!this.finishFlag && duck_x >= this.start_x) { //鴨が波紋のスタート位置に来たら波紋が広がり始める | |
if(this.radius <= MAX_RADIUS) { | |
this.radius += this.velocity; //波紋の広がり | |
} else { | |
this.radius = 0; //波紋が画面からはみ出すと消える | |
this.finishFlag = 1; | |
} | |
} else if (duck_x <= this.start_x) { | |
this.finishFlag = 0; //鴨がまた戻って来たら初めから | |
this.radius = 0; | |
} | |
} | |
// 描画メソッド | |
// これが呼ばれるとオブジェクトを描画 | |
render(context) { | |
context.beginPath(); | |
context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI); | |
context.stroke(); | |
} | |
} | |
// 鴨クラス | |
class Duck { | |
constructor(x, y, width, height) { | |
this.x = x; | |
this.start_x = x; | |
this.y = y; | |
this.width = width; | |
this.height = height; | |
this.velocity = 0.1; // この速度で右に移動 | |
} | |
update() { | |
if(this.x <= WIDTH) { | |
this.x += this.velocity; | |
} else { | |
this.x = this.start_x; | |
} | |
} | |
render(context) { | |
context.beginPath(); | |
context.fillStyle = 'rgb(0, 0, 0)'; | |
context.rect(this.x, this.y, this.width, this.height); | |
context.fill(); | |
} | |
} | |
// 波紋オブジェクトを管理する配列 | |
const rippleList = []; | |
// 鴨が15px移動するごとに新しい波紋を生成 | |
for(var i=0; i<WIDTH; i+=15){ | |
rippleList.push(new Ripple(150+i, 150, 0.2)); | |
} | |
// 鴨インスタンス生成 | |
duck = new Duck(148, 148, 4, 4); | |
function loop(timestamp) { | |
// 前の描画を消す | |
context.clearRect(0, 0, WIDTH, HEIGHT); | |
// 各オブジェクトの状態を更新 | |
duck.update(); | |
rippleList.forEach((obj) => obj.update(duck.x)); | |
// 各オブジェクトを描画 | |
duck.render(context); | |
rippleList.forEach((obj) => obj.render(context)); | |
// requestAnimationFrameを呼び出す | |
window.requestAnimationFrame((ts) => loop(ts)); | |
} | |
// アニメーションを開始する | |
window.requestAnimationFrame((ts) => loop(ts)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment