觉得好请点赞支持!
<div id="box">
<img :src="{{info.url1}}" alt="">
<img :src="{{info.url2}}" alt="">
</div>
<div onClick='shotPoster'>生成海报</div>
<img :src="{{canvasSrc}}" alt="这就是生成的那个海报!">
const getBase64 = () => {
// 替换成自己项目里面的请求
getInfo({xxx: 'xxx'}).then((res) => {
// 返回值的图片统一做base64处理
const info = res
Promise.all([
imgUrl2Base64(info.url1),
imgUrl2Base64(info.url2)
]).then(([url1, url2]) => {
info.url1 = url1
info.url2 = url2
this.setState({info})
})
});
}
// 将正经url转成base64格式。不能转的就在后面加个useCredential防缓存。
const imgUrl2Base64 = (url) => {
return new Promise((resolve, reject) => {
if (url) {
const img = document.createElement('img')
img.crossOrigin = 'anonymous'
img.src = url
// img.src = url + '?timeStamp=' + new Date().getTime()
img.onload = function () {
// 要先确保图片完整获取到,这是个异步事件
try {
const canvas = document.createElement('canvas') // 创建canvas元素
var width = img.width // 确保canvas的尺寸和图片一样
var height = img.height
canvas.width = width
canvas.height = height
canvas.getContext('2d').drawImage(img, 0, 0, width, height) // 将图片绘制到canvas中
const dataURL = canvas.toDataURL('image/png') // 转换图片为dataURL
console.log('确实转成了dataURL')
resolve(dataURL)
} catch (err) {
console.error(err)
resolve(url + `?useCredential=${new Date().getTime()}`)
}
}
img.onerror = function (err) {
console.error(err)
resolve(url + `?useCredential=${new Date().getTime()}`)
}
} else {
resolve(url)
}
})
}
// 生成海报。
import html2canvas from 'html2canvas'
const shotPoster = () => {
// 先把页面抬到顶头。防止截图不全。
scrollTo(0, 0)
const _this = this
const container = document.querySelector('#box')
html2canvas(container, {
useCORS: true,
backgroundColor: null,
// 设置canvas尺寸与所截图尺寸相同,防止白边
width: container.offsetWidth,
height: container.offsetHeight - 2,
x: 0,
y: 0
}).then(function (canvas) {
const a = canvas.toDataURL('image/png')
_this.setState({
canvasSrc: a
})
})
}