JSFiddle - React, Tailwind, and code Playground
HTML
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<canvas id="canvas" style="border: 1px solid red"></canvas>
</body>
</html>
JavaScript
var box = new Array();
var width = window.innerWidth;
var height = window.innerHeight;
var field = document.getElementById('canvas');
function createBox(e) { // this box will always fail collision detection at the upper-left corner
box.push(100); // x-value is normally mouse position
box.push(100); // y-value is normally mouse position
box.push(-5); // x-speed is normally random
box.push(-5); // y-speed is normally random
}
function redraw() {
field.ctx.clearRect(0,0,width,height);
for(var i = 0; i < box.length; i+=4) {
if(box[i] < 0) box[i+2] *= -1;
else if(box[i] > width) box[i+2] *= -1;
if(box[i+1] < 0) box[i+3] *= -1;
else if(box[i+1] > height) box[i+3] *= -1;
box[i] += box[i+2];
box[i+1] += box[i+3];
field.ctx.strokeRect(box[i], box[i+1], 4, 4);
}
}
field.width = width;
field.height = height;
field.ctx = field.getContext('2d');
field.ctx.strokeStyle = 'rgba(0,0,0,1)';
setInterval(redraw, 200);
addEventListener('click', createBox, false);