見出し画像

Canvasで大量の円に重力を与える

Canvas(JavaScript)の勉強をしています。

前回は、円(ボール)に重力を与えました。

今回は、円を大量に増やしました。

let RBall = [];
let NUM = 100;

function initialize() {
	canvas = document.body.querySelector('canvas');
	canvas.width = 640;
	canvas.height = 335;
	ctx = canvas.getContext('2d');

	// class
	for (let i = 0; i < NUM; i++) {
		velX = getRandom(-10, 10);
		velY = getRandom(-10, 10);
		graY = getRandom(0, 1);
		RBall[i] = new releaseBalls(velX, velY, graY);
	}
}

function render() {
	ctx.clearRect(0, 0, canvas.width, canvas.height);

	ctx.fillStyle = 'limegreen';
	ctx.fillRect(0, 0, canvas.width, canvas.height);

	for (let i = 0; i < NUM; i++) {
		RBall[i].draw();
	}

	window.requestAnimationFrame(render);
}

class releaseBalls {
	constructor(velX, velY, graY) {
		this.locX = canvas.width / 2;
		this.locY = canvas.height / 3;
		this.velX = velX;
		this.velY = velY;
		this.graY = graY;
	}

	draw() {
		this.velY = this.velY + this.graY;
		this.locX = this.locX + this.velX;
		this.locY = this.locY + this.velY;

		ctx.beginPath();
		ctx.arc(this.locX, this.locY, 5, 0, Math.PI * 2, false);
		ctx.fillStyle = 'blue';
		ctx.fill();

		if (this.locY < 0 || this.locY > canvas.height) {
			this.velY = this.velY * -1;
		} else if (this.locX < 0 || this.locX > canvas.width) {
			this.velX = this.velX * -1;
		}
	}
}

参考にしたもの

参考にしているのは今回も、田所淳さんの『Processing クリエイティブ・コーディング入門−コードが生み出す創造表現』です。

こちらは、CanvasではなくProcessingの本なのですが、考え方は同じなのですごく参考になります。


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