Skip to content Skip to sidebar Skip to footer

Draw Portion Of An Huge Image On A Canvas Across Browsers

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 i

Solution 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);
}

Post a Comment for "Draw Portion Of An Huge Image On A Canvas Across Browsers"