Skip to content

Instantly share code, notes, and snippets.

@linw1995
Last active June 6, 2017 14:22
Show Gist options
  • Save linw1995/d5f0aa326860f4f52c703ef549de67e5 to your computer and use it in GitHub Desktop.
Save linw1995/d5f0aa326860f4f52c703ef549de67e5 to your computer and use it in GitHub Desktop.
Animation of RGB Circles
html(lang="en")
body
canvas#Canvas(width="128" height="128")
const frameN = 30;
const delay = 1000.0 / frameN;
var loopStack = Array();
var canvas = document.getElementById("Canvas");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var ctx = canvas.getContext("2d");
var canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
var R = Math.sqrt(canvasWidth * canvasHeight) / 5
function drawPixel(x, y, r, g, b, a) {
const index = (x + y * canvasWidth) * 4;
canvasData.data[index + 0] = r;
canvasData.data[index + 1] = g;
canvasData.data[index + 2] = b;
canvasData.data[index + 3] = a;
}
function updateCanvas() {
ctx.putImageData(canvasData, 0, 0);
}
class Circle {
constructor(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
}
set(x, y) {
this.x = x;
this.y = y;
}
brightness(x, y) {
const dx = this.x - x;
const dy = this.y - y;
const dis = Math.sqrt(dx * dx + dy * dy) / this.r;
if (dis > 1) {
return 0;
} else {
return 255;
}
}
}
loop = function () {
while (loopStack.length) {
clearInterval(loopStack.pop());
}
step = 0;
circles = [new Circle(0, 0, R), new Circle(0, 0, R), new Circle(0, 0, R)];
hx = canvasWidth / 2;
hy = canvasHeight / 2;
label = setInterval(function () {
θ = 2.0 * Math.PI / frameN * step;
for (i = 0; i < 3; i++) {
θ0 = 2.0 * Math.PI / 3 * i;
const r = R * 0.6;
x = hx - r * Math.sin(θ0) - r * Math.sin(θ0 + θ);
y = hy - r * Math.cos(θ0) - r * Math.cos(θ0 + θ);
circles[i].set(x, y);
}
for (x = 0; x < canvasWidth; x++) {
for (y = 0; y < canvasHeight; y++) {
cr = circles[0].brightness(x, y);
cg = circles[1].brightness(x, y);
cb = circles[2].brightness(x, y);
if (cr > 0 || cg > 0 || cb > 0) {
drawPixel(x, y, cr, cg, cb, 255);
} else {
drawPixel(x, y, 0, 0, 0, 0);
}
}
}
updateCanvas();
if (step >= frameN) {
clearInterval(label);
}
step++;
}, delay);
loopStack.push(label);
};
setInterval(loop, delay * frameN);
#Canvas {
width:64px;
height:64px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment