Draw portion of an huge image on a canvas across b

2019-08-27 00:00发布

问题:

I'm trying to draw a portion of a very big image inside a canvas, everything works correctly on desktop but on mobile the image is either blurred or cropped incorrectly.

The code is really simple:

var c = document.getElementById("c");
var ctx = c.getContext("2d");
var img = document.getElementById("image");
ctx.drawImage(img, 0, 0, 400, 400, 0, 0, 400, 400);

and the html is:

<img id="image" src="https://c402277.ssl.cf1.rackcdn.com/photos/13338/images/hero_full/17_259_Earth_Hour_Social_Web_1600x600_v2.jpeg?1490108175" style="display:none">
<canvas id="c" width="400" height="400"></canvas>

if I use fairly normal image like the one in the above html everything works consistently across browsers, if I use a bigger one like this the result is inconsistent between desktop and mobile

These are the two fiddles:

  • regular image: https://jsfiddle.net/al3x88/as2nxwtk/7/
  • big image: https://jsfiddle.net/al3x88/as2nxwtk/9/

and these are two screenshots of the big one, desktop (left) and mobile (right)

回答1:

Hi you can use following formula to manage image which has high resolution.

var c = document.getElementById("c");
var ctx = c.getContext("2d");
var img = document.getElementById("image");

var widthPer = 400; // Desire width to draw in pixel as per original image size.
var heightPer = 400; // Desire height to draw in pixel as per original image size.


var drawImgWidth = (img.width/img.naturalWidth)*widthPer;  // calculated width in pixel.
var drawImgHeight = (img.height/img.naturalHeight)*heightPer; // calculated height in pixel.


if(img.width != img.naturalWidth) {
     ctx.drawImage(img, 0, 0, drawImgWidth, drawImgHeight, 0, 0, 400, 400);
}
else {
     ctx.drawImage(img, 0, 0, widthPer, heightPer, 0, 0, 400, 400);
}