JSFiddle - React, Tailwind, and code Playground
by alexb
HTML
<canvas></canvas>
CSS
body {
margin: 0;
}
canvas {
height: 100vh;
width: 100vw;
}
JavaScript
let start;
let canvas, ctx;
let w, h;
let texture;
let textureRatio = 2000/1333;
let particles;
const NUM_PARTICLES = 50;
const init = () => {
canvas = document.querySelector('canvas');
w = canvas.width = canvas.clientWidth;
h = canvas.height = canvas.clientHeight;
ctx = canvas.getContext('2d');
texture = new Image();
texture.src = 'https://i.imgur.com/De50vK3.png';
particles = [];
for (let i = 0; i < NUM_PARTICLES; i++) {
particles.push({
x: 0,
y: 0,
vx: (0.5 - Math.random()) * 100,
vy: (0.5 - Math.random()) * 100,
r: 0,
rv: (0.5 - Math.random()) * 5 ,
});
}
start = performance.now();
}
const update = d => {
for (const p of particles) {
p.x += p.vx * d;
p.y += p.vy * d;
p.r += p.rv * d;
}
ctx.globalAlpha -= d;
}
const render = () => {
ctx.save();
ctx.clearRect(0, 0, w, h);
ctx.translate(w/2, h/2);
for (const p of particles) {
const textureWidth = 100;
const textureHeight = textureWidth / textureRatio;
ctx.save();
ctx.translate(p.x, p.y);
ctx.rotate(p.r);
ctx.drawImage(
texture,
-textureWidth/2,
-textureHeight/2,
textureWidth,
textureHeight);
ctx.restore();
}
ctx.restore();
}
let lastTime;
const tick = t => {
if (!lastTime) lastTime = t;
update((t - lastTime) / 1000);
render();
lastTime = t;
requestAnimationFrame(tick);
}
init();
requestAnimationFrame(tick);