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>
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>
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!