Last active
May 23, 2019 14:45
-
-
Save jjmalina/bb3769a3d022cb5a5930598e60cca07a to your computer and use it in GitHub Desktop.
Scaling a 2D static canvas element
This file contains hidden or 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 scaleCanvas(canvas, options = {}) { | |
const imageData = canvas.toDataURL('image/png'); | |
const context = canvas.getContext('2d'); | |
const xScale = options.width !== undefined ? options.width / canvas.width : options.height / canvas.height; | |
const yScale = options.height !== undefined ? options.height / canvas.height : options.width / canvas.width; | |
const newWidth = Math.round(canvas.width * xScale); | |
const newHeight = Math.round(canvas.height * yScale); | |
canvas.width = newWidth; | |
canvas.newHeight = newHeight; | |
canvas.style = ''; | |
// The image must be redrawn onto the scaled canvas because changing its height clears all the data | |
return new Promise((resolve, reject) => { | |
const img = new Image; | |
img.onload = () => { | |
context.drawImage(img, 0, 0, newWidth, newHeight); | |
resolve(canvas); | |
}; | |
img.onerror = (err) => { | |
reject(err); | |
}; | |
img.src = imageData; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment