JSFiddle - React, Tailwind, and code Playground
JavaScript
const WIDTH = 500;
const HEIGHT = 500;
//
// 前準備。
//
// canvas要素を作る。
const canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
// コンテキストを取得しておく。
const context = canvas.getContext('2d');
// body要素に追加する。
document.body.appendChild(canvas);
// 円(Circle)クラスを用意する。
// 円クラスは更新メソッドと描画メソッドを持っている。
class Circle {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
this.velocity = 2; // この速度で膨張・縮小を繰り返す。
}
// 更新メソッド。
// これが呼ばれるとオブジェクトの状態を更新する。
update() {
// 半径が100より大きいか50より小さかったら膨張速度を反転する。
if(this.radius > 100 || this.radius < 50) {
this.velocity = -this.velocity;
}
this.radius += this.velocity; // 半径をvelocityだけ増やす。
}
// 描画メソッド。
// これが呼ばれるとオブジェクトを描画する。
render(context) {
context.beginPath();
context.fillStyle = 'rgb(255, 0, 0)'; // 赤色
context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
context.fill();
}
}
// 同様に四角形クラス。
class Rectangle {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.velocityX = 2; // この速度で横に移動する。
}
update() {
if(this.x < 0 || this.x > WIDTH) {
this.velocityX = -this.velocityX;
}
this.x += this.velocityX;
}
render(context) {
context.beginPath();
context.fillStyle = 'rgb(0, 0, 255)'; // 青色
context.rect(this.x, this.y, this.width, this.height);
context.fill();
}
}
//
// メイン処理。
//
// オブジェクトを管理する配列。
const objects = [];
// 円と四角形を1個ずつ追加。
objects.push(new Circle(150, 150, 50));
objects.push(new Rectangle(350, 350, 50, 50));
// ループさせる関数。
function loop(timestamp) {
// 前の描画を消す。
context.clearRect(0, 0, WIDTH, HEIGHT);
// 各オブジェクトの状態を更新する。
objects.forEach((obj) => obj.update());
// 各オブジェクトを描画する。
objects.forEach((obj) => obj.render(context));
// requestAnimationFrameを呼び出す。
window.requestAnimationFrame((ts) => loop(ts));
}
//...