Canvas floating boxes (vertical)
by sungsoonz
HTML
<canvas width="600" height="400"></canvas>
CSS
canvas {
background: black;
}
JavaScript
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
let boxes = [];
let mousePos = {x: 0, y: 0};
let selectedBox;
canvas.addEventListener('click', function(e) {
mousePos.x = e.x;
mousePos.y = e.y;
});
class Box {
constructor(index, x, y, speed) {
this.index = index;
this.x = x;
this.y = y;
this.speed = speed;
this.width = 14;
this.height = 28;
}
draw() {
ctx.fillStyle = 'rgba(250,130,0,0.7)';
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
let box;
for (let i = 0; i < boxes.length; i++) {
box = boxes[i];
box.y -= box.speed;
if (box.y+box.height < 0) {
box.y = canvas.height;
}
box.draw();
}
requestAnimationFrame(render);
}
function init() {
let tempX, tempY, tempSpeed;
for (let i = 0; i < 100; i++) {
tempX = Math.random() * canvas.width;
tempY = Math.random() * canvas.height;
tempSpeed = Math.random() + 0.1;
boxes.push(new Box(i, tempX, tempY, tempSpeed));
}
}
init();
render();