How to do a html5 canvas scale animation?

by elisha_langworth , in category: Javascript , 3 months ago

How to do a html5 canvas scale animation?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 3 months ago

@elisha_langworth 

To create a scale animation on a HTML5 canvas, you can use the requestAnimationFrame() method in JavaScript to continuously update the scale of the canvas element.


Here is an example code snippet to demonstrate a scale animation on a HTML5 canvas:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html>
<head>
    <title>Canvas Scale Animation</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>

    <script>
        const canvas = document.getElementById('myCanvas');
        const ctx = canvas.getContext('2d');

        let scale = 1;
        let scaleDirection = 1;

        function animate() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // Update the scale factor
            scale += 0.01 * scaleDirection;
            if (scale > 2 || scale < 0.5) {
                scaleDirection *= -1;
            }

            // Apply the scale transformation to the canvas context
            ctx.save();
            ctx.scale(scale, scale);

            // Draw a rectangle with the scaled canvas context
            ctx.fillStyle = 'blue';
            ctx.fillRect(50, 50, 100, 100);

            ctx.restore();

            // Request the next frame
            requestAnimationFrame(animate);
        }

        animate();
    </script>
</body>
</html>


In this code snippet, we first create a HTML5 canvas element and obtain its 2D rendering context. We then define a global variable scale to keep track of the current scale factor and scaleDirection to control the direction of scaling.


The animate() function is called recursively using requestAnimationFrame() to continuously update the scale factor and apply the scale transformation to the canvas context. We draw a rectangle on the canvas and apply the scale transformation to it.


The scale animation will continue indefinitely, oscillating between a scale factor of 0.5 and 2. You can adjust the animation speed by changing the increment value in the scale += 0.01 * scaleDirection; line.