<canvas width="250" height="250" id="myCanvas"></canvas>
var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); var x = 0, y = 0; var dx = 2, dy = 3; function draw() { // clear the whole screen ctx.clearRect(0, 0, canvas.width, canvas.height); // draw a circle ctx.fillStyle="#FF0000"; ctx.beginPath(); ctx.arc(x, y, 15, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); // update position x = x + dx; y = y + dy; // check for bounce if(x >= canvas.width || x <= 0) dx = dx * -1; if(y >= canvas.height || y <= 0) dy = dy * -1; } setInterval(draw, 10);
canvas { border: 1px dotted red; margin: 15px; }