Animation in Canvas simple html js code Example

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 context
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");

        // Initial position of the object
        var x = 50;
        var y = 50;

        // Speed and direction of the object
        var dx = 2;
        var dy = 2;

        // Function to draw the object
        function draw() {
            // Clear the canvas
            ctx.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 object
            x += dx;
            y += dy;

            // Check boundaries and change direction if necessary
            if (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 loop
            requestAnimationFrame(draw);
        }

        // Call the draw function to start the animation
        draw();
    </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:

 

Canvas Animation

Comments :

Post a Comment