Canvasでうじゃうじゃを作る
Canvas(JavaScript)を勉強しています。
今回は、ランダムを使いたくて、たくさん(1000個)の点がうじゃうじゃ動いているものを作りました。
ランダムはMDNのこのページにいくつかのバリエーションが載っていました。
うじゃうじゃ
let movePoint = [];
let NUM = 1000;
function initialize() {
canvas = document.body.querySelector('canvas');
ctx = canvas.getContext('2d');
for (let i = 0; i < NUM; i++) {
movePoint[i] = new Mover();
}
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'lightyellow';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < NUM; i++) {
movePoint[i].draw();
}
window.requestAnimationFrame(render);
}
class Mover {
constructor() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Math.PI * 2, false);
ctx.fillStyle = 'blue';
ctx.fill();
this.x = this.x + getRandomArbitrary(-2, 2);
this.y = this.y + getRandomArbitrary(-2, 2);
}
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
1つ1つの点は、円(arc)で作っています。
Classで円を設定して、それをforで1000回繰り返して、うじゃうじゃを作っています。
ランダムは、
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
で作ってますが、普通にrandom()を使うとうじゃうじゃせずに、すべての点が右下に向かって移動してしますでの、これを使ってます。
参考にしたもの
参考にしているのは、前回とおなじく、田所淳さんの『Processing クリエイティブ・コーディング入門−コードが生み出す創造表現』です。
こちらは、CanvasではなくProcessingの本なのですが、考え方は同じなのですごく参考になります。
ブラウザで確認
ブラウザで見たい方は下のサイトにあります。私の個人サイト(素材置場)です。
この記事が気に入ったらサポートをしてみませんか?