Skip to content

Instantly share code, notes, and snippets.

@arifd
Last active January 30, 2020 10:32
Show Gist options
  • Save arifd/431a366bba18397610f643660fcccfd4 to your computer and use it in GitHub Desktop.
Save arifd/431a366bba18397610f643660fcccfd4 to your computer and use it in GitHub Desktop.
Let the browser scale/resize an image for you
// If you want to load an image but have it be scaled.
// instead of 'new Image();' call this function, with onload being its 3rd argument.
function createScaledImageFromSource(src, scaleFactor, callback = null)
{
let img = new Image();
img.src = src;
let outImage = new Image();
img.onload = () =>
{
let width = img.width * scaleFactor;
let height = img.height * scaleFactor;
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
// draw the img onto canvas (it will be resized)
ctx.drawImage(img, 0, 0, width, height);
// now send that resized image back out
outImage.src = canvas.toDataURL();
outImage.onload = callback;
}
return outImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment