JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="1000" height="500" style="border: 1px solid #0095DD;"></canvas>
JavaScript
function distance(x1, y1, x2, y2) {
x = x1 - x2;
y = y1 - y2;
return Math.sqrt(x * x + y * y);
}
class Scene {
constructor(config = {}) {
//default options
this.canvasId = 'canvas';
this.width = 1000;
this.height = 500;
//default objectsConfig
this.objectsConfig = {
'ball1': {
'class': 'Ball',
'config': {
'x': 50,
'y': 100,
'r': 30,
'color': 'blue'
}
},
'ball2': {
'class': 'Ball',
'config': {
'x': 140,
'y': 40,
'r': 30,
'color': 'green'
}
},
'dependents': {
'listenCollision': {'ball1': 'ball2'},
},
};
Object.assign(this, config);
this.context = document.getElementById(this.canvasId).getContext('2d');
this.objects = [];
}
initObjects() {
for (let key in this.objectsConfig) {
if (key !== 'dependents') {
Object.assign(this.objectsConfig[key].config, {'scene': this});
/* this.objects[key] = new this.objectsConfig[key].class(this.objectsConfig[key].config);*/
this.objects[key] = new Ball(this.objectsConfig[key].config);
console.log(this.objectsConfig[key].config);
}
}
}
}
class Ball {
constructor(config) {
//default options
this.x = 20;
this.y = 20;
this.r = 10;
this.color = 'green';
this.speedX = 4;
this.speedY = 8;
this._scene = config.scene;
Object.assign(this, config);
}
draw() {
this._scene.context.fillStyle = this.color;
this._scene.context.beginPath();
this._scene.context.arc(this.x, this.y, this.r, 0,...