Toggle navigation
☰
HTML
CSS
Scripting
Database
<!DOCTYPE html> <html> <body> <canvas id="animCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas> <script> var canvas = document.getElementById("animCanvas"); var ctx = canvas.getContext("2d"); var x = 0; var dx = 2; // Speed in x direction function animate() { // 1. Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // 2. Draw the object ctx.fillStyle = "#0070C0"; ctx.fillRect(x, 50, 50, 50); // 3. Update the state x += dx; // Bounce back at the edges if (x > canvas.width - 50 || x < 0) { dx = -dx; } // Request the next frame requestAnimationFrame(animate); } // Start the animation animate(); </script> </body> </html>