Javascript examples for Canvas:Example
Calculate random bounce angles
<html> <head> <title>Bouncing ball example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.js"></script> <script type="text/javascript"> $(window).load(function(){/* w ww . ja v a 2 s.c o m*/ var canvas = document.getElementById('mainCanvas'); var ctx; var x = 300; var y = 150; var dx = 1; var dy = 1; function init() { ctx = canvas.getContext('2d'); return setInterval(draw, 10); } function draw() { ctx.clearRect(0,0,300,300); ctx.beginPath(); ctx.arc(x, y, 20, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); x += dx; y += dy; if (x > 300 || x < 0) { dx *= -1; } if (y > 300 || y < 0) { dy *= -1; } } init(); }); </script> </head> <body> <canvas id="mainCanvas" style="background-color:white;" height="300" width="300"> Canvas element not loading. </canvas> </body> </html>