The HTML image of the canvas is much lower than the original image. What for?

I have a simple HTML document with an image and a canvas element. The src image is just a high quality image found on the Internet, just to illustrate my point. When I try to draw an image on the canvas, the resulting image of the canvas is very uneven and of poor quality. I can’t understand why. Similar questions were asked here, but I could not find an answer that seemed to solve the problem. If someone finds another post with a working answer, please let me know. Any help is appreciated. Thanks in advance!

Here is the JSfiddle with the code: https://jsfiddle.net/vey309b0/5/

HTML:

<p>the original image:</p>
<img id="img_cam" src="https://4.bp.blogspot.com/k8IX2Mkf0Jo/U4ze2gNn7CI/AAAAAAAA7xg/iKxa6bYITDs/s0/HOT+Balloon+Trip_Ultra+HD.jpg" width="400">
<p>the canvas with drawn image:</p>
<canvas id="imgcanvas" width="400"></canvas>

JavaScript:

var canvas = document.getElementById("imgcanvas");
var img_can = document.getElementById("img_cam");
var ctx = canvas.getContext("2d");
var imgWidth = img_can.width;
var imgHeight = img_can.height;
canvas.width = imgWidth;
canvas.height = imgHeight;
ctx.drawImage(img_can, 0, 0, imgWidth, imgHeight);
+4
1

naturalWidth naturalHeight , CSS, .

var canvas = document.getElementById("imgcanvas");
var ctx = canvas.getContext("2d");
var img_can = document.getElementById("img_cam");
img_can.onload = function() {
  canvas.width = this.naturalWidth;
  canvas.height = this.naturalHeight;
  ctx.drawImage(this, 0, 0);
};
img_can.src = img_can.getAttribute('data-src');
<p>
the original image:
</p>
<img id="img_cam" data-src="https://4.bp.blogspot.com/-k8IX2Mkf0Jo/U4ze2gNn7CI/AAAAAAAA7xg/iKxa6bYITDs/s0/HOT+Balloon+Trip_Ultra+HD.jpg" width="400">
<p>
the canvas with drawn image:
</p>
<canvas id="imgcanvas" style="width:400px;"></canvas>
Hide result

onload img.

+2

Source: https://habr.com/ru/post/1681812/


All Articles