html2canvas
场景:使用 html2canvas 将长图保存到 iOS 和 Android
使用最新的版本暂未发现图片内容偏移的问题
可能遇到的问题
1. 也可能是
- Android 的部分手机会保存失败,可能是 web 图片的 base64 太长,超出了安卓的最大值
handleDown() {
let _this = this
Toast.loading({
message: '生成海报...',
forbidClick: true,
duration: 0
})
setTimeout(() => {
let img = _this.$refs['image']
let isIos = navigator.appVersion.match(/(iphone|ipad|ipod)/gi) || false
html2canvas(img, {
useCORS: true, // 允许图片跨域
allowTaint: false,
scale: isIos ? 1 : 0.6,
taintTest: true,ß
dpi: window.devicePixelRatio
}).then(function(canvas) {
_this.photoUrl = canvas.toDataURL('image/png')
_this.downloadIamge(_this.photoUrl, 'poster.png')
})
}, 3000)
},
downloadIamge(imgsrc, name) {
var image = new Image()
var canvas = document.createElement('canvas')
var context = canvas.getContext('2d')
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous')
image.src = imgsrc
image.style.objectFit = 'contain'
image.onload = () => {
canvas.width = image.width
canvas.height = image.height
context.drawImage(image, 0, 0, image.width, image.height)
// 得到图片的base64编码数据
var url = canvas.toDataURL('image/png')
let deleteString = 'data:image/png;base64,'
var index = url.indexOf(deleteString)
if (index === 0) {
let url2 = url.slice(deleteString.length)
utils.postMessage('save_image', url2) // 将图片的base64字符串 传给移动端
Toast.clear()
} else {
this.$toast('保存失败请重试')
}
}
}
网友评论