見出し画像

Canvasで円を動かして、上下左右で跳ね返る(Class版)

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

今回は、前回↓と同じ動きをClassを使って作ってみました。

Classで作る

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

	moveRect = new Mover();
}

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

	// background
	ctx.fillStyle = 'lightyellow';
	ctx.fillRect(0, 0, canvas.width, canvas.height);

	moveRect.drawRect();
	window.requestAnimationFrame(render);
}

class Mover {
	constructor() {
		this.x = 100;
		this.y = 100;
		this.dx = 5;
		this.dy = 3;
	}
	drawRect() {
		ctx.beginPath();
		ctx.fillStyle = 'green';
		ctx.arc(this.x, this.y, 10, 0, Math.PI * 2, false);
		ctx.fill();

		if (this.x < 0 || this.x > canvas.width) {
			this.dx = this.dx * -1;
		}
		if (this.y < 0 || this.y > canvas.height) {
			this.dy = this.dy * -1;
		}
		this.x = this.x + this.dx;
		this.y = this.y + this.dy;
	}
}

無事に動いているのですが、実際はよくわかっていません。

moveRect = new Mover();

これで、Classを読み込んで、

moveRect.drawRect();

これで書き出す、という認識です。

で、

window.requestAnimationFrame(render);

これで、アニメーションしています。

本当はClassの中をすべて変数にして、いろんな円を作りやすくするんでしょうね。次回は、この円が大量に動いているものをあげます。

参考にしたもの

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

こちらは、CanvasではなくProcessingの本なのですが、Canvasの本はあまりないので仕方なく使っています。私はProcessingから勉強を始めました。

ブラウザで確認

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


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