我在使用 IE9 时遇到了问题,在 Chrome 中,下载了一些图像,但它们已损坏。我为 IE9 找到的唯一解决方案是在新选项卡上打开图像,然后我可以右键单击并另存为。我制作了下一个代码,用于使用 html2canvas 将 div 区域(地图的容器)下载为图像。
function download_image() {
if($.browser.safari) {// Fix for Chrome
var transform=$(".gm-style>div:first>div").css("transform");
var comp=transform.split(","); //split up the transform matrix
var mapleft=parseFloat(comp[4]); //get left value
var maptop=parseFloat(comp[5]); //get top value
$(".gm-style>div:first>div").css({ //get the map container. not sure if stable
"transform":"none",
"left":mapleft,
"top":maptop,
});
}
html2canvas([$("#div_id")[0]], {
logging: false,
useCORS: true,
onrendered: function (canvas) {
if ($("#downloadimg").length > 0)
$("#downloadimg").remove();
var fileName = "file_name.png";
if (/\bMSIE|Trident\b/.test(navigator.userAgent) && $.browser.version.match(/9.0|10.0|11.0/)) {//Only for IE 9, 10 and 11
download_image_IE(canvas, fileName);
}
else {
$("body").append("<a id='downloadimg' download='" + fileName + "' href='" + canvas.toDataURL("image/png").replace("image/png", "image/octet-stream") + "'><a/>");
}
if ($("#downloadimg").length > 0)
$("#downloadimg")[0].click();
if($.browser.safari) {// Fix for Chrome
$(".gm-style>div:first>div").css({
left:0,
top:0,
"transform":transform
});
}
}
});
}
function download_image_IE(canvas, filename) {
if ($.browser.version.match(/9.0/)){ //Only for IE9
var w = window.open();
$(w.document.body).html('<img src="'+ canvas.toDataURL() +'"/>');
}
else{
var image = canvas.toDataURL();
image = image.substring(22); // remove data stuff
var byteString = atob(image);
var buffer = new ArrayBuffer(byteString.length);
var intArray = new Uint8Array(buffer);
for (var i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i);
}
var blob = new Blob([buffer], { type: "image/png" });
window.navigator.msSaveOrOpenBlob(blob, filename);
}
}