Skip to content

Instantly share code, notes, and snippets.

@i1u5
Last active March 26, 2020 17:14
Show Gist options
  • Save i1u5/8458e2171fa297c5796205bd9d32817a to your computer and use it in GitHub Desktop.
Save i1u5/8458e2171fa297c5796205bd9d32817a to your computer and use it in GitHub Desktop.
Vanilla JS function to scale images proportionally using canvas and return a Base64 encoded image
function scaleImage(url, width = 1024, quality = 1.0) {
let img = new Image();
img.onload = function () {
let canvas = document.createElement("canvas"),
context = canvas.getContext("2d");
canvas.width = width;
canvas.height = width * (img.height / img.width);
context.drawImage(img, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL('image/jpeg', quality);
};
img.src = url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment