<canvas width="250" height="250" id="myCanvas"></canvas>
// 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
canvas { border: 1px dotted red; margin: 15px; }