Making things move
<!DOCTYPE html> <html> <head> //from ww w . ja va 2 s. c o m <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { let canvas = $("#myCanvas"); let context = canvas.get(0).getContext("2d"); let canvasWidth = canvas.width(); let canvasHeight = canvas.height(); let playAnimation = true; let x = 0; let startButton = $("#startAnimation"); let stopButton = $("#stopAnimation"); startButton.hide(); startButton.click(function() { $(this).hide(); stopButton.show(); playAnimation = true; animate(); }); stopButton.click(function() { $(this).hide(); startButton.show(); playAnimation = false; }); function animate() { x++; context.clearRect(0, 0, canvasWidth, canvasHeight); context.fillRect(x, 250, 10, 10); if (playAnimation) { setTimeout(animate, 33); }; }; animate(); }); </script> </head> <body> <canvas id="myCanvas" width="500" height="500"> <!-- Insert fallback content here --> </canvas> <div> <button id="startAnimation">Start</button> <button id="stopAnimation">Stop</button> </div> </body> </html>