Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Created April 6, 2017 01:50
Show Gist options
  • Save animatedlew/ade48791c96a36a663a0ba4c35ba4da8 to your computer and use it in GitHub Desktop.
Save animatedlew/ade48791c96a36a663a0ba4c35ba4da8 to your computer and use it in GitHub Desktop.
const canvas = document.createElement("canvas");
canvas.width = 400;
canvas.height = 400;
const ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
let objs = [{
x: 0,
y: 0,
z: -160,
r: 10,
s: 0,
c: "rgba(128, 0, 0, 0.5)"
}, {
x: 0,
y: 0,
z: -180,
r: 10,
s: 0,
c: "rgba(128, 128, 0, 0.5)"
}, {
x: 0,
y: 0,
z: -200,
r: 10,
s: 0,
c: "rgba(0, 128, 128, 0.5)"
}];
const vpx = canvas.width/2;
const vpy = canvas.height/2;
let x = vpx, y = vpy;
canvas.addEventListener('mousewheel', (e) => {
let delta = e.wheelDelta > 0 ? 5 : -5;
let scale = 1.2;
for (let o of objs) {
o.z += delta * scale;
scale *= 0.8;
}
});
canvas.addEventListener('mousemove', e => {
x = e.clientX - vpx;
y = e.clientY - vpx;
});
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let o of objs) {
let fl = 250;
let scale = fl / (fl + o.z);
o.s = scale * o.r;
o.x = vpx + x * scale;
o.y = vpy + y * scale;
ctx.beginPath();
ctx.arc(o.x-o.s/2, o.y-o.s/2, o.s < 0 ? 0 : o.s, 0, 2*Math.PI);
ctx.fillStyle = o.c;
ctx.fill();
ctx.stroke();
}
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment