Home > Web Front-end > JS Tutorial > How to Achieve Smooth Image Resizing with JavaScript Canvas?

How to Achieve Smooth Image Resizing with JavaScript Canvas?

Linda Hamilton
Release: 2024-10-22 22:10:03
Original
1082 people have browsed it

How to Achieve Smooth Image Resizing with JavaScript Canvas?

Smooth Image Resizing with JavaScript Canvas

When resizing images using canvas, it's common to encounter issues with smoothness. Unlike software like Photoshop or browsers that employ algorithms like bicubic or bilinear, canvas doesn't have built-in smoothing features.

To achieve smooth resizing, you can use down-stepping. While browsers typically resort to linear interpolation during image resizing, down-stepping employs bilinear interpolation to produce more refined results. By breaking down the process into multiple steps, you can approximate bi-cubic results.

Consider the following code snippet:

<code class="js">var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();

img.onload = function () {

    // set size proportional to image
    canvas.height = canvas.width * (img.height / img.width);

    // step 1 - resize to 50%
    var oc = document.createElement('canvas'),
        octx = oc.getContext('2d');

    oc.width = img.width * 0.5;
    oc.height = img.height * 0.5;
    octx.drawImage(img, 0, 0, oc.width, oc.height);

    // step 2
    octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);

    // step 3, resize to final size
    ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,
    0, 0, canvas.width, canvas.height);
}
img.src = "image.jpg";</code>
Copy after login

The first step reduces the image to 50% of its original size. The second step downscales the intermediate image again, resulting in a final 25% reduction. Finally, the third step adjusts the image to its desired size.

By repeating the downscaling process multiple times, you effectively approximate the smoother bi-cubic interpolation technique. This approach grants canvas the ability to resize images with enhanced smoothness, approximating the quality seen in software programs and browsers.

The above is the detailed content of How to Achieve Smooth Image Resizing with JavaScript Canvas?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template