跨浏览器在画布上绘制巨大图像的一部分 [英] 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.
代码非常简单:
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);
并且html是:
<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>
如果我使用上面html中的图像,那么一切正常在浏览器中都能正常工作;如果我使用较大的图像,例如
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
这是两个小提琴:
- 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)
推荐答案
您可以使用以下公式来管理具有高分辨率的图像.
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);
}
这篇关于跨浏览器在画布上绘制巨大图像的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!