Home > Web Front-end > JS Tutorial > body text

How to Achieve Smooth Resized Images with HTML Canvas?

Susan Sarandon
Release: 2024-10-22 22:04:03
Original
437 people have browsed it

How to Achieve Smooth Resized Images with HTML Canvas?

Smoothing Images with Canvas

Resizing images with HTML canvas is a common task, but achieving smoothness can be a challenge. While image editing software like Photoshop offers various interpolation algorithms such as bicubic and bilinear, it's unclear if canvas supports these options.

<code class="js">var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 234;
ctx.drawImage(img, 0, 0, 300, 234);
document.body.appendChild(canvas);</code>
Copy after login

The above code snippet resizes an image using canvas, but the resized image lacks smoothness.

To address this, the concept of down-stepping can be employed. Browsers typically use linear interpolation for resizing, which can result in aliasing. By breaking the down-scaling process into multiple steps, one can achieve a result closer to bi-cubic interpolation.

Consider the following modified code:

<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 = "//i.imgur.com/SHo6Fub.jpg";</code>
Copy after login

This code performs multiple resizing steps in succession, progressively reducing the image size and applying interpolation. The result is an image with smoother edges and improved visual quality.

The above is the detailed content of How to Achieve Smooth Resized Images with HTML 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!