Skip to content

Instantly share code, notes, and snippets.

@sortofsleepy
Last active September 23, 2024 13:09
Show Gist options
  • Save sortofsleepy/39f908078ce31d3fe85e64dd7df3d644 to your computer and use it in GitHub Desktop.
Save sortofsleepy/39f908078ce31d3fe85e64dd7df3d644 to your computer and use it in GitHub Desktop.
Basic Image scaling
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);
}
@sortofsleepy
Copy link
Author

sortofsleepy commented Sep 23, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment