Skip to content

Instantly share code, notes, and snippets.

@atesgoral
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atesgoral/670d77c10bf854f70131 to your computer and use it in GitHub Desktop.
Save atesgoral/670d77c10bf854f70131 to your computer and use it in GitHub Desktop.
Balls.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Balls.</title>
<style>
canvas { background-color: black; }
</style>
</head>
<body>
<canvas width="600" height="600" id="stage"></canvas>
<script>
var stage = document.getElementById("stage");
var stageW = stage.width,
stageH = stage.height;
var ctx = stage.getContext("2d");
function drawBall(ball) {
ctx.fillStyle = "#0080ff";
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
var balls = [];
var ballRadius = 20;
for (var i = 0; i < 10; i++) {
balls.push({
x: Math.random() * (stageW - ballRadius * 2) + ballRadius,
y: Math.random() * (stageH - ballRadius * 2) + ballRadius,
r: ballRadius,
vx: (Math.random() - 0.5) * 10,
vy: (Math.random() - 0.5) * 10
});
}
function draw() {
ctx.globalAlpha = 0.2;
ctx.drawImage(
ctx.canvas,
5,
5,
ctx.canvas.width - 10,
ctx.canvas.height - 10,
0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.globalAlpha = 0.02;
ctx.fillStyle = "#401000";
ctx.fillRect(0, 0, stageW, stageH);
ctx.globalAlpha = 1;
balls.forEach(drawBall);
}
var accX = 0;
accY = 0.5;
function process() {
balls.forEach(function (ball) {
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.x < ballRadius) {
ball.x = ballRadius;
ball.vx = -ball.vx;
} else if (ball.x > stageW - ballRadius) {
ball.x = stageW - ballRadius;
ball.vx = -ball.vx;
}
if (ball.y < ballRadius) {
ball.y = ballRadius;
ball.vy = -ball.vy;
} else if (ball.y > stageH - ballRadius) {
ball.y = stageH - ballRadius;
ball.vy = -ball.vy;
}
ball.vy += accY;
ball.vx += accX;
});
}
function tick() {
draw();
process();
window.setTimeout(tick, 1000 / 25);
}
tick();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment