Skip to content

Instantly share code, notes, and snippets.

@jjmalina
Last active May 23, 2019 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjmalina/bb3769a3d022cb5a5930598e60cca07a to your computer and use it in GitHub Desktop.
Save jjmalina/bb3769a3d022cb5a5930598e60cca07a to your computer and use it in GitHub Desktop.
Scaling a 2D static canvas element
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