<template>
<div>
<img :src="posterImg" v-if="posterImg" class="poster"/>
<div id="poster" class="poster" ref="poster" v-else>
<img id="bgimg" class="bgimg" crossorigin="anonymous" :src="`${posterInfo.bg}?time=${new Date().valueOf()}`">
<img id="banner" class="banner" crossorigin="anonymous" :src="`${posterInfo.personnel_share_img}?time=${new Date().valueOf()}`">
<div id="title" class="title">{{ posterInfo.activity_name || '' }}</div>
<div id="info" class="info view2">
<div style="flex: 1;display: flex;align-items: center;">
<img id="infoavatar" class="info-avatar" crossorigin="anonymous" :src="`${posterInfo.avatar_url}?time=${new Date().valueOf()}`">
<div class="info-left">
<div class="info-name">{{ posterInfo.personnel_name }}</div>
<div class="info-dec">分享给你</div>
</div>
</div>
<img id="infocode" class="info-code" crossorigin="anonymous" :src="`${posterInfo.qr_img_url}?time=${new Date().valueOf()}`">
</div>
</div>
</div>
</template>
图片地址后添加?time=${new Date().valueOf()},不然会报图片跨域报错
原因:这是因为你img是在缓存数据中读取的 并没有访问远程这个图片的时候没有携带请求头。
确保你的图片服务器支持CORS访问,也就是会返回Access-Control-Allow-Origin等响应头;文章来源地址https://www.toymoban.com/news/detail-784074.html
import html2canvas from 'html2canvas'
//响应式,高度根据宽度比例响应,定位
makeDom(){
let _this = this;
this.$nextTick(function(){
let poster = document.getElementById('poster');
let posterWidth = poster.offsetWidth;
let bgimg = document.getElementById('bgimg');
let banner = document.getElementById('banner');
let title = document.getElementById('title');
let info = document.getElementById('info');
let infoavatar = document.getElementById('infoavatar');
let infocode = document.getElementById('infocode');
poster.style.height = posterWidth*1.35+'px';
bgimg.style.height = posterWidth*1.35+'px';
banner.style.top = posterWidth*0.5+'px';
banner.style.height = posterWidth*0.4+'px';
title.style.top = posterWidth*0.93+'px';
info.style.top = posterWidth*1.05+'px';
infoavatar.style.width = posterWidth*0.16+'px';
infoavatar.style.height = posterWidth*0.16+'px';
infocode.style.width = posterWidth*0.23+'px';
infocode.style.height = posterWidth*0.23+'px';
setTimeout(function() {
_this.makePoster();
},2000)
})
},
//生成图
makePoster(){
let that = this;
html2canvas(this.$refs.poster, {
backgroundColor: '#fff',
useCORS: true,//开启跨域
imageTimeout: 6000,
logging: true,
//allowTaint: true,
}).then(canvas => {
let dataURL = canvas.toDataURL('image/png');
let file = that.base64toFile(dataURL)
//file就是图片,可做一个图片上传到自己的资源服务器
}).catch((err) => {})
},
base64toFile(dataurl, filename = "file") {
let arr = dataurl.split(",");
let mime = arr[0].match(/:(.*?);/)[1];
let suffix = mime.split("/")[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime,
});
},
文章来源:https://www.toymoban.com/news/detail-784074.html
到了这里,关于html2canvas截图生产海报图片的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!