Skip to content

Instantly share code, notes, and snippets.

@chabb
Last active March 22, 2018 23:30
Show Gist options
  • Select an option

  • Save chabb/0c3986c296bb19fcbf8ae85997b8eaf4 to your computer and use it in GitHub Desktop.

Select an option

Save chabb/0c3986c296bb19fcbf8ae85997b8eaf4 to your computer and use it in GitHub Desktop.
Animated rectangle
<canvas id="canvas" width="900px" height="600px"></canvas>
<script src="./index.js"></script>
let randShift = .3;
let quadW = 15;
let quadH = 15;
let q = [ -quadW / 2, quadH / 2, quadW, quadH ];
let targetQ = [];
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let width = 900;
let height = 600;
let steps = 25;
let inc = 1 / steps;
let colors = [];
function setup() {
for (let i = 0, k = 1; i < height - quadH; i += quadH, k++) {
for (let j = 0; j < width - quadW; j += quadW) {
targetQ.push([
[q[0] + r(k), q[1] + r(k)],
[q[0] + q[2] + r(k), q[1] + r(k)],
[q[0] + q[2] + r(k), q[1] + q[3] + r(k)],
[q[0] + r(k), q[1] + q[3] + r(k)]]);
colors.push(`rgba(${Math.floor(Math.random() * (255 - k / 5 ))},
${Math.floor(Math.random() * (255 - k * (k / 10)))},
${Math.floor(Math.random() * (255 - k * (k / 5)))}, 1)`);
}
}
}
let t = 0;
function draw() {
let tg = 0;
ctx.clearRect(0, 0, width, height);
for (let i = 0, k = 1; i < height - quadH; i += quadH, k++) {
ctx.save();
ctx.translate(0, quadH * k);
for (let j = 0; j < width - quadW; j += quadW) {
let base = {
x: targetQ[0][0][0],
y: targetQ[0][0][1]
};
let x = targetQ[tg][0][0], y = targetQ[tg][0][1];
let q1 = interpolate(base, {x, y}, t);
x = targetQ[tg][1][0];
y = targetQ[tg][1][1];
base = {
x: targetQ[0][1][0],
y: targetQ[0][1][1]
}
let q2 = interpolate(base, {x, y}, t);
x = targetQ[tg][2][0];
y = targetQ[tg][2][1];
base = {
x: targetQ[0][2][0],
y: targetQ[0][2][1]
}
let q3 = interpolate(base, {x, y}, t);
x = targetQ[tg][3][0];
y = targetQ[tg][3][1];
base = {
x: targetQ[0][3][0],
y: targetQ[0][3][1]
}
let q4 = interpolate(base, {x, y}, t);
ctx.translate(quadW, 0);
ctx.fillStyle = colors[tg];
ctx.beginPath();
ctx.moveTo(q1[0], q1[1]);
ctx.lineTo(q2[0], q2[1]);
ctx.lineTo(q3[0], q3[1]);
ctx.lineTo(q4[0], q4[1]);
ctx.closePath();
ctx.fill();
tg++;
}
ctx.restore();
}
t = t + inc;
window.requestAnimationFrame(draw);
}
setup();
draw();
function r(i) {
let base = -i * randShift;
return base + Math.random() * (i * randShift - base)
}
function interpolate(a, b, frac) // points A and B, frac between 0 and 1
{
let nx = a.x+ (b.x - a.x) * frac;
let ny = a.y+ (b.y - a.y) * frac;
return [ nx, ny ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment