Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Resize Image Using HTML Canvas in JavaScript

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = "https://images.pexels.com/photos/3408744/pexels-photo-3408744.jpeg?auto=compress&cs=tinysrgb&dpr=2";

img.onload = function () {
    // set height proportional to destination image
    canvas.height = canvas.width * (img.height / img.width);
    // step 1 - resize to 75%
    const oc = document.createElement('canvas');
    const octx = oc.getContext('2d');
    // Set the width & height to 75% of image
    oc.width = img.width * 0.75;
    oc.height = img.height * 0.75;
    // step 2, resize to temporary size
    octx.drawImage(img, 0, 0, oc.width, oc.height);
    // step 3, resize to final size
    ctx.drawImage(oc, 0, 0, oc.width * 0.75, oc.height * 0.75, 0, 0, canvas.width, canvas.height);
}
Source by www.delftstack.com #
 
PREVIOUS NEXT
Tagged: #Resize #Image #Using #HTML #Canvas #JavaScript
ADD COMMENT
Topic
Name
9+8 =