Home > Web Front-end > JS Tutorial > How to Overcome Jagged Edges and Blurry Results When Resizing Images with Canvas?

How to Overcome Jagged Edges and Blurry Results When Resizing Images with Canvas?

DDD
Release: 2024-10-22 20:40:03
Original
656 people have browsed it

How to Overcome Jagged Edges and Blurry Results When Resizing Images with Canvas?

Resolving Smoothing Issues When Resizing Images Using Canvas in JavaScript

Resizing images using canvas in JavaScript can sometimes result in noticeable jagged edges or blurring. To achieve smooth resizes, a technique known as down-stepping can be employed.

In most browsers, linear interpolation is used for resizing by default. Bi-cubic interpolation, which produces smoother results, involves using a larger neighborhood of pixels. However, browsers typically don't implement bi-cubic interpolation directly.

The down-stepping approach involves resizing the image repeatedly, each time using a smaller scale factor. This mimics the behavior of bi-cubic interpolation while still utilizing linear interpolation in the underlying browser.

The following code snippet demonstrates how to implement down-stepping:

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";
Copy after login

This code creates a temporary canvas, oc, and iteratively resizes the image, eventually drawing it onto the final canvas. Each resizing step uses linear interpolation, but by combining them, the overall effect approximates bi-cubic interpolation.

The imageSmoothingQuality property can also be used to control the smoothing quality in Chrome, providing a more direct means of achieving smoothness, but it is not yet supported in all browsers.

The above is the detailed content of How to Overcome Jagged Edges and Blurry Results When Resizing Images with 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template