Created
February 12, 2020 16:31
-
-
Save Pamblam/e9840b171fe68d64b6c1d9e1cccf126a to your computer and use it in GitHub Desktop.
Functions that take an image uri and scale them to fit or fill a given area;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function loadImage(src){ | |
return new Promise((r,e)=>{ | |
var img = new Image(); | |
img.onload = ()=>r(img); | |
img.onerror = e; | |
img.src = src; | |
}); | |
} | |
async function scaleAndFitImage(src, w, h) { | |
var img = await loadImage(src); | |
var canvas = document.createElement('canvas'); | |
canvas.width = w; canvas.height = h; | |
var ctx = canvas.getContext('2d'); | |
var scale = Math.min(canvas.width / img.width, canvas.height / img.height); | |
var x = (canvas.width / 2) - (img.width / 2) * scale; | |
var y = (canvas.height / 2) - (img.height / 2) * scale; | |
ctx.drawImage(img, x, y, img.width * scale, img.height * scale); | |
return canvas.toDataURL(); | |
} | |
async function scaleAndCoverImage(src, w, h) { | |
var img = await loadImage(src); | |
var canvas = document.createElement('canvas'); | |
canvas.width = w; canvas.height = h; | |
var ctx = canvas.getContext('2d'); | |
var x = y = 0, offsetX = 0.5, offsetY = 0.5; | |
var iw = img.width, | |
ih = img.height, | |
r = Math.min(w / iw, h / ih), | |
nw = iw * r, // new prop. width | |
nh = ih * r, // new prop. height | |
cx, cy, cw, ch, ar = 1; | |
if (nw < w) ar = w / nw; | |
if (Math.abs(ar - 1) < 1e-14 && nh < h) ar = h / nh; // updated | |
nw *= ar; | |
nh *= ar; | |
cw = iw / (nw / w); | |
ch = ih / (nh / h); | |
cx = (iw - cw) * offsetX; | |
cy = (ih - ch) * offsetY; | |
if (cx < 0) cx = 0; | |
if (cy < 0) cy = 0; | |
if (cw > iw) cw = iw; | |
if (ch > ih) ch = ih; | |
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h); | |
return canvas.toDataURL(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment