Graphic Animation in Canvas simple HTML JS code
Here's a simple HTML and JavaScript code snippet that creates an animation using the HTML5 canvas element:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Canvas Animation</title><style>canvas {border: 1px solid black;}</style></head><body><canvas id="myCanvas" width="500" height="500"></canvas><script>// Get the canvas element and its contextvar canvas = document.getElementById("myCanvas");var ctx = canvas.getContext("2d");// Initial position of the objectvar x = 50;var y = 50;// Speed and direction of the objectvar dx = 2;var dy = 2;// Function to draw the objectfunction draw() {// Clear the canvasctx.clearRect(0, 0, canvas.width, canvas.height);// Draw the object (a simple circle in this case)ctx.beginPath();ctx.arc(x, y, 20, 0, Math.PI * 2);ctx.fillStyle = "blue";ctx.fill();ctx.closePath();// Update the position of the objectx += dx;y += dy;// Check boundaries and change direction if necessaryif (x + dx > canvas.width || x + dx < 0) {dx = -dx;}if (y + dy > canvas.height || y + dy < 0) {dy = -dy;}// Request animation frame to create a smooth animation looprequestAnimationFrame(draw);}// Call the draw function to start the animationdraw();</script></body></html>
In this example, a blue circle moves around the canvas. The draw function is responsible for clearing the canvas, drawing the circle, updating its position, and checking boundaries to change its direction when it hits the canvas edges. The requestAnimationFrame function is used to create a smooth animation loop. You can modify the initial position, speed, size, and other properties to customize the animation as you like.
Output:
Comments :
Post a Comment