JavaScript»オブジェクト指向»メソッド ぽこぽこしているバブルの色をかえるメソッド
ファイル名: js-oop/quest_00668.html
下のソースコードに必要なプログラムを書き加えて、ぽこぽこしているバブルの色が200ミリ秒ごとにランダムに変化するプログラムを完成させてください。
ソースコード
class Bubble {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = 0;
// 新しいバブル作成時にも、ランダムな色を設定しておく
this.changeColor();
}
enlarge() {
this.radius += 1;
}
rise(dy) {
this.y -= dy;
}
// ここに、色をランダムに変化させるメソッド changeColor を書いてね
}
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
let bubbles = [];
setInterval(() => {
const x = Math.floor(Math.random() * (320 - 32));
const y = Math.floor(Math.random() * 320);
bubbles.push(new Bubble(x, y));
}, 200);
// 200ミリ秒ごとに全ての泡オブジェクトの色をランダムに変える
// この中でchangeColorメソッドをつかっている
setInterval(() => {
bubbles.forEach(bubble => bubble.changeColor());
}, 200);
const repaint = function() {
context.clearRect(0, 0, 320, 320);
bubbles.forEach(b => {
// バブルを描くときは、colorプロパティの値をfillStyleに設定する
context.fillStyle = b.color;
context.beginPath();
context.arc(b.x, b.y, b.radius, 0, Math.PI * 2);
context.fill();
b.rise(2);
b.enlarge();
});
bubbles = bubbles.filter(bubble => bubble.radius < 32);
};
setInterval(repaint, 25);
ヒント
ランダムな色を返す関数の書き方を思い出そう!