Vue + html2canvas截图时 不能使用跨域图片的解决方案
需要修改三个地方:
1、修改源码 node_modules/html2canvas/dist/html2canvas.js
5710行和5714行
case 2:
this.context.logger.debug("Added image " + key.substring(0, 256));
return [4 /*yield*/, new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () { return resolve(img); };
img.onerror = reject;
//ios safari 10.3 taints canvas with data urls unless crossOrigin is set to anonymous
if (isInlineBase64Image(src) || useCORS) {
// img.crossOrigin = 'anonymous'; // 第一个修改的地方
img.crossOrigin = '';
}
// img.src = src; // 第二个修改的地方
if(src.indexOf('data:image')>-1){ // 图片地址后加时间 base64图片不变
// base64 图片操作
img.src = src;
}else{
//path 图片操作
img.src = src+"?"+new Date().getTime();
}
if (img.complete === true) {
// Inline XML images may fail to parse, throwing an Error later on
setTimeout(function () { return resolve(img); }, 500);
}
if (_this._options.imageTimeout > 0) {
setTimeout(function () { return reject("Timed out (" + _this._options.imageTimeout + "ms) loading image"); }, _this._options.imageTimeout);
}
})];
第三个修改的地方
html2canvas(myRef.value, {
dpi: window.devicePixelRatio * 2,
backgroundColor: "#fff",
useCORS: true, // 第三个修改的地方
allowTaint: true, //允许跨域(默认false)
scale: 2,
async: true,
}).then((canvas) => {
state.dataImg = canvas.toDataURL("image/png",1);
state.showImg = true
Toast.clear()
});