html2canvas
場景:使用 html2canvas 將長圖保存到 iOS 和 Android
使用最新的版本暫未發(fā)現(xiàn)圖片內(nèi)容偏移的問題
可能遇到的問題
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編碼數(shù)據(jù)
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('保存失敗請重試')
}
}
}