Categories
JavaScript Answers

How to scale an image to fit on canvas with JavaScript?

Spread the love

To scale an image to fit onto a canvas with JavaScript, you need to calculate the appropriate scaling factor and then draw the image onto the canvas with the desired dimensions.

For example we write:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scale Image to Fit Canvas</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="300"></canvas>
    <script>
        // Get the canvas element and its context
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // Create an image element
        var img = new Image();
        img.src = 'your_image_url_here.jpg'; // Replace 'your_image_url_here.jpg' with the URL of your image

        // When the image is loaded, scale and draw it on the canvas
        img.onload = function() {
            // Calculate the scaling factors to fit the image onto the canvas
            var scaleX = canvas.width / img.width;
            var scaleY = canvas.height / img.height;
            var scale = Math.min(scaleX, scaleY); // Use the smaller scale factor

            // Calculate the new dimensions of the image
            var scaledWidth = img.width * scale;
            var scaledHeight = img.height * scale;

            // Calculate the position to center the image on the canvas
            var x = (canvas.width - scaledWidth) / 2;
            var y = (canvas.height - scaledHeight) / 2;

            // Clear the canvas and draw the scaled image
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, x, y, scaledWidth, scaledHeight);
        };
    </script>
</body>
</html>

In this code, we load the image using the Image constructor.

When the image is loaded, calculate the scaling factors (scaleX and scaleY) to fit the image onto the canvas. Use the smaller scale factor to ensure the entire image fits within the canvas.

Next we calculate the new dimensions of the scaled image (scaledWidth and scaledHeight).

Then we calculate the position (x and y) to center the image on the canvas.

Finally, we clear the canvas and draw the scaled image using the drawImage method of the canvas context (ctx.drawImage).

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *