Skip to content

Instantly share code, notes, and snippets.

@HynekS
Created September 19, 2020 09:51
Show Gist options
  • Save HynekS/4befe1e8aac20a52c7688a401e67aeee to your computer and use it in GitHub Desktop.
Save HynekS/4befe1e8aac20a52c7688a401e67aeee to your computer and use it in GitHub Desktop.
Helper function to draw bitmap image on html canvas (centered, preserved aspect ratio)
function drawImageScaled({ context, image }) {
const canvas = context.canvas
const hRatio = canvas.width / image.width
const vRatio = canvas.height / image.height
const ratio = Math.min(hRatio, vRatio)
const centerShift_x = (canvas.width - image.width * ratio) / 2
const centerShift_y = (canvas.height - image.height * ratio) / 2
context.clearRect(0, 0, canvas.width, canvas.height)
context.drawImage(
image,
0,
0,
image.width,
image.height,
centerShift_x,
centerShift_y,
image.width * ratio,
image.height * ratio,
)
}
export default drawImageScaled
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment