HTML JS

HOW TO RESIZE IMAGES IN JAVASCRIPT

IMAGE RESIZE HTML

01

JUST AN EMPTY CANVAS <canvas id="can"></canvas>

JAVASCRIPT  RESIZE (A)

02

NEW IMAGE + GET CANVAS var img = new Image(),  can = document.getElementById("can"), ctx = can.getContext("2d");

JAVASCRIPT  RESIZE (B)

03

RESIZE ON IMAGE LOAD img.onload = () => {   let   w = Math.floor(img.naturalWidth * 0.5),   h = Math.floor(img.naturalHeight * 0.5);   can.width = w; can.height = h;   ctx.drawImage(img, 0, 0, w, h); }; GO! img.src = "IMAGE.PNG";

RESIZED DOWNLOAD

04

CREATE DOWNLOAD LINK var anc = document.createElement("a"); anc.setAttribute("download", "R.PNG"); anc.href = canvas.toDataURL("image/png");

THIS MAY NOT ALWAYS WORK anc.click();

BETTER LET USERS CLICK ON LINK anc.innerHTML = "Download"; document.body.appendChild(anc);