Created
September 19, 2020 09:51
-
-
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)
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 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