0

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);
ROHAN
  • 9
  • 1
  • 4

1 Answers1

2

This question has more or less been answered here: https://stackoverflow.com/a/19262385/3767825.

The main problem is that JavaScript actually doesn't include any good algoritms to resize images, it just reduces number of pixels in the image (except for Google Chrome which currently have a experimental imageSmoothingQuality feature implemented).

There are also third party libraries and code attempts to implement bicubic image sampling and bilinear image sampling. Please have a look at this page for more details and code examples: https://www.strauss-engineering.ch/posts/js-bilinear-interpolation.html.

qorsmond
  • 1,246
  • 1
  • 18
  • 29
jonasdev
  • 696
  • 5
  • 11