Skip to main content

Archive

Show more

Transformations in Canvas

Transformations in Canvas

Transformations in HTML canvas allow you to manipulate the position, rotation, scale, and skew of shapes and drawings. These transformations enable you to create dynamic and interactive graphics. Here's how to apply transformations in the canvas:


1. Translation

Translation moves the entire coordinate system by a specified distance along the x and y axes. Use the translate() method to apply translation:

// Translate by dx units along the x-axis and dy units along the y-axis
ctx.translate(dx, dy);

This shifts the origin of the canvas to the new position.


2. Rotation

Rotation rotates shapes and drawings around a specified point. Use the rotate() method to apply rotation:

// Rotate by angle radians around the origin (0, 0)
ctx.rotate(angle);

This rotates the canvas clockwise or counterclockwise around the origin.


3. Scaling

Scaling changes the size of shapes and drawings along the x and y axes. Use the scale() method to apply scaling:

// Scale by scaleX along the x-axis and scaleY along the y-axis
ctx.scale(scaleX, scaleY);

This enlarges or shrinks the canvas and its contents.


4. Applying Transformations

You can apply multiple transformations sequentially to achieve complex transformations:

// Translate to a new position
ctx.translate(100, 100);

// Rotate around the new origin
ctx.rotate(Math.PI / 4);

// Scale the drawing
ctx.scale(2, 2);

This translates the canvas, rotates it by 45 degrees, and then scales it by a factor of 2 along both axes.


Example:

Here's a simple example demonstrating how to apply transformations in the canvas:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Transformations Example</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400" style="border:1px solid black"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');
        
        // Translate to a new position
        ctx.translate(100, 100);
        
        // Rotate around the new origin
        ctx.rotate(Math.PI / 4);
        
        // Scale the drawing
        ctx.scale(2, 2);
        
        // Draw a rectangle
        ctx.fillRect(50, 50, 50, 50);
    </script>
</body>
</html>

Conclusion

Transformations in the canvas allow you to manipulate the position, rotation, and scale of shapes and drawings, enabling you to create dynamic and interactive graphics in web development. By applying translation, rotation, and scaling, you can achieve a wide range of visual effects and transformations, enhancing the user experience.

Comments