Last active
September 23, 2024 13:09
-
-
Save sortofsleepy/39f908078ce31d3fe85e64dd7df3d644 to your computer and use it in GitHub Desktop.
Basic Image scaling
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 scaleImage(img, ctx, targetWidth, targetHeight) { | |
const widthRatio = targetWidth / img.width; | |
const heightRatio = targetHeight / img.height; | |
const scale = Math.max(widthRatio, heightRatio); | |
let finalWidth = img.width * scale; | |
let finalHeight = img.height * scale; | |
// calcualte overlap, if any, between final width and contianer with | |
// TODO may need to make sure which value is bigger first | |
let dx = finalWidth - baseWidth; | |
let dy = finalHeight - baseHeight; | |
ctx.drawImage(img, -dx / 2, -dy/2, finalWidth, finalHeight); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A basic image scaling function for rendering an image onto a canvas and making sure it's scaled and fitted (relatively) properly. Assumes landscape images.
May not work in all situations.