问题是图片是 svg,有必要使用 XMLSerializer(),而且我认为有时 html2canvas 无法处理 primeFaces 的布局,所以如果你对 importNode 修复的 css 有问题。为我工作:
//don't forget to declare all js libs and files on html page
//targetElem - id of map, like a $('#map')
function screenshotMap(targetElem) {
var nodesToRecover = [];
var svgElem = targetElem.find('svg');
var serializer = new XMLSerializer();
//screenshotAreaId - north layoutUnit of layout this variable need for
//"update" north layoutUnit
var oldNode = document.getElementById("screenshotAreaId");
//convert all svg's to canvas, filling an arrays for turn back canvas to svg
svgElem.each(function (index, node) {
var parentNode = node.parentNode;
//skip nested svg's in "parent" svg, canvg will handle "parent"
if(parentNode.tagName != 'DIV'){
return true;
}
var canvas = document.createElement('canvas');
var svg = parentNode.querySelector('svg');
var svgString = serializer.serializeToString(svg);
//canvg lib
canvg(canvas, svgString);
nodesToRecover.push({
parent: parentNode,
child: node
});
parentNode.removeChild(node);
parentNode.appendChild(canvas);
});
//html2canvas lib, "screenshot map" download file
html2canvas(targetElem, {
onrendered: function (canvas) {
var img = canvas.toDataURL('image/png').replace("image/png", "image/octet-stream");
window.location.href = img;
//removing canvas, turn back svg's
var canvasElem = targetElem.find('canvas');
canvasElem.each(function (index, node) {
var parentNode = node.parentNode;
parentNode.removeChild(node);
parentNode.appendChild(nodesToRecover[index].child);
});
//"update" layoutUnit if you have problems with css
var newNode = document.importNode(oldNode, true);
document.getElementById("layout").appendChild(newNode);
}
});
}
你会在这里找到canvg:https ://github.com/gabelerner/canvg
你会在这里找到 html2canvas:http: //html2canvas.hertzen.com/