Categories
JavaScript Answers

How to resize (downscale) high quality image with HTML5 canvas and JavaScript?

Spread the love

To resize (downscale) high quality image with HTML5 canvas and JavaScript, we call the scale method.

For instance, we write

const setCanvasSize = (canvas, rate) => {
  const scaleRate = rate;
  canvas.width = window.innerWidth * scaleRate;
  canvas.height = window.innerHeight * scaleRate;
  canvas.style.width = window.innerWidth + "px";
  canvas.style.height = window.innerHeight + "px";
  canvas.getContext("2d").scale(scaleRate, scaleRate);
};

to set the canvas width and height with

canvas.width = window.innerWidth * scaleRate;
canvas.height = window.innerHeight * scaleRate;
canvas.style.width = window.innerWidth + "px";
canvas.style.height = window.innerHeight + "px";

then we scale its content by the scaleRate horizontally and vertically with

canvas.getContext("2d").scale(scaleRate, scaleRate);

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *