解决-使用html2canvas截取页面时,页面的div背景图无法截取并跨域
示例
第一步安装依赖
npm install html2canvas --save
第二步使用依赖
import html2canvas from 'html2canvas';
第三步如何在div里面使用
<div class="phone" ref="phoneContent">
<p>这里是文字标题</p>
<img :src="staticImgUrl + 'mobile/init_t1.png'" alt=""/>
</div>
<Phone
:data="data"
:selectedIndex="selectedIndex"
@onEditer="onEditer"
@onDeleleItem="onDeleleItem"
ref="phoneContent"
>
</Phone>
第四步在methods如何调用
onFormSubmit(){
const element = this.$refs.phoneContent;
const element = this.$refs.phoneContent.$el;
html2canvas(element,{
dpi: window.devicePixelRatio * 2,
useCORS: true,
allowTaint: true,
async: true,
}).then((canvas) => {
let img = new Image();
img.src = canvas.toDataURL('image/png');
console.log("img.src",img.src);
});
}
第五步使用以上代码截图里面的图片是空白如何解决
1.修改源码 node_modules/html2canvas/dist/html2canvas.js
this.context.logger.debug("Added image " + key.substring(0, 256));
return [4 , new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () { return resolve(img); };
img.onerror = reject;
if (isInlineBase64Image(src) || useCORS) {
img.crossOrigin = '';
}
if(src.indexOf('data:image')>-1){
img.src = src;
}else{
img.src = src+"?"+new Date().getTime();
}
if (img.complete === true) {
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);
}
})];