JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="500px" height="500px"></canvas>
JavaScript
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
class Entity {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {}
}
class Rect extends Entity {
constructor(x, y, width, height, color) {
super(x, y);
this.width = width;
this.height = height;
this.color = color;
}
draw(ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.fill();
}
}
class Circle extends Entity {
constructor(x, y, radius, color) {
super(x, y);
this.radius = radius;
this.color = color;
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
}
}
let objects = [
new Rect(10, 10, 20, 20, 'red'),
new Rect(30, 50, 30, 20, 'orange'),
new Circle(120, 50, 10, 'green'),
new Circle(170, 20, 12, 'blue'),
];
function draw() {
context.clearRect(0, 0, 500, 500);
objects.forEach(obj => {
obj.x += 0.1; // каждый объект можно менять, и после вызова draw, изменения будут отображены
obj.draw(context);
});
requestAnimationFrame(draw);
}
draw();