JSFiddle - React, Tailwind, and code Playground
by Alexander
HTML
<canvas id="canvas" width="500" height="300"></canvas>
CSS
canvas {
border: 1px solid gray;
}
JavaScript
function Canvas() {
var c = document.getElementById("canvas"),
ctx = c.getContext("2d"),
interval;
this.canvasObjectCollection = [];
this.clear = function() {
ctx.clearRect(0,0,c.width,c.height);
}
this.drawObjects = function() {
for(k in this.canvasObjectCollection) {
var o = this.canvasObjectCollection[k]; //shorthand for object in collection
if (o.movingSpeed) {
o.x += Math.random() * o.movingSpeed;
o.y += Math.random() * o.movingSpeed;
}
ctx.fillStyle = o.fillColor;
ctx.fillRect(o.x, o.y, o.width, o.height);
}
}
this.startDrawCycle = function() {
var that = this;
that.interval = window.setInterval(function() {
that.clear();
that.drawObjects();
//console.log('end of sequence');
}, 1);
}
this.stopDrawCycle = function() {
window.clearInterval(this.interval);
//console.log('should stop drawing cycle');
}
this.addCanvasObject = function(canvasObject) {
this.canvasObjectCollection.push(canvasObject);
}
this.printCanvasObjectCollection = function() {
//console.log(this.canvasObjectCollection);
}
}
function CanvasObject(options) {
this.width = 10;
this.height = 10;
this.x = 0;
this.y = 0;
this.fillColor = 'gray';
this.movingSpeed = 0;
this.movingDirection = 0;
for(k in options['properties']) {
this[k] = options['properties'][k];
}
this.move = function(settings) {
//console.log(settings);
if (settings.direction == 'left') this.x -= settings.speed;
if (settings.direction == 'right') this.x += settings.speed;
if (settings.direction == 'up') this.y -= settings.speed;
if (settings.direction == 'down') this.y += settings.speed;
}
//rm ??
this.moveTowardsPoint = function(point, speed) {
var xDiff = (this.x - point.x)/speed;
var yDiff = (this.y - point.y)/speed;
this.x -= xDiff;
this.y -= yDiff;
}
}
var canvas = new...