0

I am trying to clip part of original image using X,Y coordinates and W,H dimensions, and place it to canvas.

Here is my codepen example

img.onload = function () {
    var boxSize = box.getBoundingClientRect();

    canvas.width = boxSize.width;
    canvas.height = boxSize.height;

    var hRatio = boxSize.width / w;
    var vRatio = boxSize.height / h;
    var ratio = Math.min(hRatio, vRatio);
    var centerShift_x = (canvas.width - w * ratio) / 2;
    var centerShift_y = (canvas.height - h * ratio) / 2;

    var ctx = canvas.getContext("2d");
    
    ctx.fillStyle = "blue";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.drawImage(
      img,
      0, 0,
      w + x, h + y,
      (-x * ratio) + centerShift_x, -y * ratio + centerShift_y,
      (w + x) * ratio, (h + y) * ratio
    );
  };

Image is significantly bigger then canvas, so I'm expecting to not loose quality, at least not too much. But in fact quality dramatically low.

So, how to not loose the quality?

Vytalyi
  • 1,637
  • 3
  • 20
  • 33
  • What do you mean by "dramatically"? For me it look ok. – Anton Aug 27 '20 at 11:42
  • 1
    Does this answer your question? [Canvas DrawImage() poor quality](https://stackoverflow.com/questions/28498014/canvas-drawimage-poor-quality) – Anton Aug 27 '20 at 11:46
  • 1
    And this: https://stackoverflow.com/questions/17861447/html5-canvas-drawimage-how-to-apply-antialiasing – Anton Aug 27 '20 at 11:46
  • I believe you need to resize programmatically the image and draw it into the canvas that way. This would bypass the errors of browser resizing. – Lajos Arpad Aug 27 '20 at 13:01

1 Answers1

0

The drawImage context method will scale your source image to the canvas size. You need to create a larger canvas than the actual image size you want, then use css/style to scale the canvas to lower resolution in the client.

You can try by just replacing the y value with something like var y=700;

jonasdev
  • 696
  • 5
  • 11