Skip to content

Instantly share code, notes, and snippets.

@Posandu
Created May 8, 2022 13:01
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 Posandu/9e6640a68877a663e4b672b1aa69c716 to your computer and use it in GitHub Desktop.
Save Posandu/9e6640a68877a663e4b672b1aa69c716 to your computer and use it in GitHub Desktop.
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = "fixed";
canvas.style.top = 0;
canvas.style.left = 0;
canvas.style.backgroundColor = "#000";
document.body.appendChild(canvas);
/* * */
let mouse = {
x: 0,
y: 0,
};
document.onmousemove = (e) => {
mouse.x = e.clientX;
mouse.y = e.clientY;
};
const colors = "3d59a1,005a9e".split`,`;
const randColor = () => `#${colors[Math.floor(Math.random() * colors.length)]}`;
const rand = (min, max) => Math.random() * (max - min) + min;
const anim = () => {
const { x, y } = mouse;
// Draw a circle
ctx.beginPath();
const size = rand(1, 2);
const color = randColor();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
let ball = { x, y, size, color };
const bounceAnim = () => {
ball.x+=rand(-1, 1);
ball.y+=rand(-1, 1);
if (ball.x > canvas.width) {
ball.x = 0;
}
if (ball.y > canvas.height) {
ball.y = 0;
}
if (ball.x < 0) {
ball.x = canvas.width;
}
if (ball.y < 0) {
ball.y = canvas.height/2;
}
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.size, 0, Math.PI * 2);
ctx.fillStyle = ball.color;
ctx.fill();
requestAnimationFrame(bounceAnim);
};
requestAnimationFrame(bounceAnim);
requestAnimationFrame(anim);
};
anim();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment