Skip to content

Instantly share code, notes, and snippets.

@x
Last active August 29, 2015 14:16
Show Gist options
  • Save x/83c906ff6e5ee8d89b6d to your computer and use it in GitHub Desktop.
Save x/83c906ff6e5ee8d89b6d to your computer and use it in GitHub Desktop.
<canvas id="display"/>
<script>
var ctx = document.getElementById('display').getContext('2d');
var speed = 5;
var fps = 60;
var circle = {
r: 10,
x: ctx.canvas.width / 2,
y: ctx.canvas.height / 2,
vx: Math.random() * speed,
vy: Math.random() * speed,
}
function drawCircle() {
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.r, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke()
}
function clearScreen() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
setInterval(function() {
// change direction on collision
if (circle.x + circle.r > ctx.canvas.width ||
circle.x - circle.r < 0) {
circle.vx *= -1;
}
if (circle.y + circle.r > ctx.canvas.height ||
circle.y - circle.r < 0) {
circle.vy *= -1;
}
// move
circle.x += circle.vx;
circle.y += circle.vy;
// redraw
clearScreen();
drawCircle();
}, 1000 / fps);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment