Skip to content

Instantly share code, notes, and snippets.

@chabb
Last active March 26, 2018 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chabb/93a0a81c68a1acb1e658a86d85226924 to your computer and use it in GitHub Desktop.
Save chabb/93a0a81c68a1acb1e658a86d85226924 to your computer and use it in GitHub Desktop.
CLICK THE CIRCLE
<canvas id="canvas" width="600px" height="400px"></canvas>
<script src="./index.js"></script>
let x = 200;
let y = 200;
let r = 100;
let color = 'black';
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let colors = [];
// so the trick is to go the center, rotate, translate by r
let acc = 0.001;
let vx = 0;
let offset = 0;
let rad = Math.PI / 180;
let colorIndex = {}, colorsRGB = [];
let clicked = [];
let hovered;
function draw() {
ctx.clearRect(0, 0, 800, 400);
for (let i = 0, j = 0; j < 360; i++, j = i * 20) {
if (!colors[i]) {
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
colors[i] = `rgba(${r}, ${g}, ${b}, 1)`;
colorsRGB[i] = [r, g, b];
colorIndex[`${r}${g}${b}`] = i;
}
ctx.save();
ctx.translate(x, y);
ctx.rotate(rad * j + offset);
ctx.translate(5, -100);
let stroke = false;
if (clicked[i]) {
clicked[i].scale += 1;
clicked[i].opacity -= 0.02;
ctx.translate( clicked[i].scale * 2, clicked[i].scale * 2);
[r, g, b] = colorsRGB[i];
let opacity = clicked[i].opacity;
colors[i] = `rgba(${r}, ${g}, ${b}, ${opacity})`;
ctx.scale(clicked[i].scale, clicked[i].scale);
} else {
stroke = hovered === i;
}
drawCircle(0, 0, 10, colors[i], stroke);
ctx.restore();
}
vx += acc;
if (vx < -0.03) {
acc = 0.0001;
}
if (vx > 0.03) {
acc = -0.0001;
}
offset += vx;
window.requestAnimationFrame(draw);
}
draw();
document.getElementById('canvas').addEventListener('click', e => {
let x = e.offsetX;
let y = e.offsetY;
let p = ctx.getImageData(x, y, 1, 1).data;
let r = p[0], g = p[1], b = p[2];
let key = `${r}${g}${b}`
let i = (colorIndex[key]);
if (i || i === 0) {
clicked[i] = {
scale: 1,
opacity: 1
}
}
});
document.getElementById('canvas').addEventListener('mousemove', e => {
let x = e.offsetX;
let y = e.offsetY;
let p = ctx.getImageData(x, y, 1, 1).data;
let r = p[0], g = p[1], b = p[2];
let key = `${r}${g}${b}`;
hovered = (colorIndex[key]);
});
function drawCircle(x, y, radius, color, stroke) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2*Math.PI);
ctx.fill();
if (stroke) {
ctx.lineWidth = 3;
ctx.stroke();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment