How to resize image to fit on a small HTML5 canvas without loosing image quality?

This is my code. I want to be able to draw image on the canvas without loosing the quality of the image.

const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
canvas.width = 360px;
canvas.height = 360px;
const img = new Image();
img.src = "some-image.jpg" // image size is 3840*2594px

var scale = Math.min(
        canvas.width / img.width,
        canvas.height / img.height
      );
      // get the top left position of the image
      var x = canvas.width / 2 - (img.width / 2) * scale;
      var y = canvas.height / 2 - (img.height / 2) * scale;

context.drawImage(img, x, y, img.width * scale, img.height * scale);

124 thoughts on “How to resize image to fit on a small HTML5 canvas without loosing image quality?”

  1. Hi there, I found your web site by way of Google whilst searching
    for a similar subject, your website got here up, it seems to
    be great. I have bookmarked it in my google bookmarks.

    Hello there, simply become alert to your weblog through Google, and
    located that it is really informative. I am gonna be careful
    for brussels. I will appreciate should you continue this in future.
    A lot of other people will likely be benefited from your writing.
    Cheers! http://www.deinformedvoters.org/hydroxychloroquine

    Reply
  2. Pingback: ivermectin generic
  3. Pingback: viagra otc uk

Leave a Comment