经过几个小时的研究,我终于找到了一个解决方案来截取一个元素的屏幕截图,即使设置了origin-clean FLAG(以防止XSS),这就是为什么你甚至可以捕获例如谷歌地图(在我的情况下)。我写了一个通用函数来获得截图。除此之外,你唯一需要的是html2canvas库(https://html2canvas.hertzen.com/)。
例子:
getScreenshotOfElement($("div#toBeCaptured").get(0), 0, 0, 100, 100, function(data) {
// in the data variable there is the base64 image
// exmaple for displaying the image in an <img>
$("img#captured").attr("src", "data:image/png;base64,"+data);
});
请记住,如果图像的大小很大,console.log()和alert()不会生成输出。
功能:
function getScreenshotOfElement(element, posX, posY, width, height, callback) {
html2canvas(element, {
onrendered: function (canvas) {
var context = canvas.getContext('2d');
var imageData = context.getImageData(posX, posY, width, height).data;
var outputCanvas = document.createElement('canvas');
var outputContext = outputCanvas.getContext('2d');
outputCanvas.width = width;
outputCanvas.height = height;
var idata = outputContext.createImageData(width, height);
idata.data.set(imageData);
outputContext.putImageData(idata, 0, 0);
callback(outputCanvas.toDataURL().replace("data:image/png;base64,", ""));
},
width: width,
height: height,
useCORS: true,
taintTest: false,
allowTaint: false
});
}