見出し画像

Canvasでうじゃうじゃを作る 2

JavaScriptの勉強をしていて、今はCanvasを中心にしています。

今回は、前回のうじゃうじゃのパート2です。
コードはほぼ同じなのですが、見た目が良い感じで気持ち悪くできたので残したくなりました。

前回のはこちら↓

怪しい色と動き

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 = 'indigo';
	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;
		this.w = getRandomArbitrary(2, 10);
	}

	draw() {
		ctx.beginPath();
		ctx.arc(this.x, this.y, this.w, 0, Math.PI * 2, false);
		ctx.fillStyle = 'crimson';
		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;
}

ブラウザで確認

ブラウザで見たい方は下のサイトにあります。私の個人サイト(素材置場)です。


この記事が気に入ったらサポートをしてみませんか?