JSFiddle - React, Tailwind, and code Playground
by dievardump
HTML
<canvas width=350 height=350></canvas>
<canvas width=350 height=350></canvas>
CSS
body { background-color: #000; text-align: center; }
canvas { margin : 15px 0; border: 1px solid #fff; }
JavaScript
function getPixels(text) {
let canvas = document.getElementsByTagName('canvas')[1],
ctx = canvas.getContext('2d'),
centerX = canvas.width / 2,
centerY = canvas.height / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "300px Helvetica";
ctx.fillStyle = '#fff';
ctx.textBaseline = 'middle';
const width = ~~ctx.measureText(text).width;
ctx.fillText(text, centerX - width / 2, centerY);
let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height),
data = imageData.data,
x = 0,
y = 0,
pxls = [];
const line = imageData.width * 4;
for (let i = 0; i < data.length; i = i + 4) {
if (data[i] !== 0) {
pxls.push({
x: x,
y: y
});
}
if (i % line === 0) {
x = 0;
y++;
} else {
x++;
}
}
return pxls;
}
const copy = document.getElementsByTagName('canvas')[0],
cctx = copy.getContext('2d'),
width = copy.width,
height = copy.height;
cctx.fillStyle = "#fff";
let particles = [],
partNb = 10000;
for (let i = 0; i < partNb; i++) {
particles[i] = {
pos: [0, 0],
from: [0, 0],
to: [0, 0]
};
}
// distribute my particles to match the pixels covered by the written number
function distribute(pxls, samePos) {
const step = pxls.length;
let available = 10000,
distrib = 0,
distributed = 0,
stepInside = 1,
index = 0,
xDiff = 0,
yDiff = 0;
while (available > 0) {
distrib = Math.min(step, available);
stepInside = Math.floor(step / distrib);
for (let i = 0, particle = null; i < distrib; i++) {
particle = particles[distributed];
index = i * stepInside;
if (samePos) {
particle.from[0] = pxls[index].x;
particle.from[1] = pxls[index].y;
} else...