// radius of ball
var r = 15;
// initial ball position - use radius so the ball doesn't start with any part over the top or left edge
var x = r, y = r;
// initial x and y velocity
var dx = 2, dy = 3;
// request 2d drawing access to the canvas
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// this function gets run every 10ms to draw a new frame and update the state of the game
function draw()
{
// clear the whole screen before drawing a new frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
// set the fill color to red
ctx.fillStyle="#FF0000";
// draw a circle and fill it in
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
// update ball's position
x = x + dx;
y = y + dy;
// check if ball is in contact with right or left edge
if(x >= canvas.width - r || x <= r)
{
// flip the sign on dx to change direction between left/right
dx = dx * -1;
}
// check if ball is in contact with right or left edge
if(y >= canvas.height - r || y <= r)
{
// flip the sign on dy to change direction between up/down
dy = dy * -1;
}
}
// start running the draw function every 10ms
setInterval(draw, 10); // 1000ms / 10ms = 100 frames per second
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.