vue2+canvs实现图片拼接
主要代码
<img v-if="mergedImage" :src="mergedImage" alt="Merged Image" />
import { saveAs } from 'file-saver'
mergeImages() {
this.images = [
'https://**************************',
'https://**************************',
'https://**************************',
'https://**************************',
'https://**************************'
]
return new Promise((resolve,reject) => {
let canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d');
const imageToLoad = this.images2.map(src => {
const img = new Image()
img.src = src
//设置跨域属性
img.crossOrigin = 'Anonymous'
return img
})
let loadCount = 0
//拼接图片的最大宽度
let maxWidth = 0
//拼接图片的总高度
let totalHeight = 0
imageToLoad.forEach(img => {
img.onload = () => {
loadCount++
maxWidth = Math.max(maxWidth,img.width)
totalHeight += img.height
if(loadCount == imageToLoad.length){
canvas.width = maxWidth
canvas.height = totalHeight
let currentHeight = 0
imageToLoad.forEach(img => {
ctx.drawImage(img,0,currentHeight)
currentHeight += img.height
});
this.mergedImage = canvas.toDataURL('image/png');
resolve(this.mergedImage)
const blob = this.dataURLToBlob(this.mergedImage2);
saveAs(blob, 'merged-image.png');
}
}
})
})
},
dataURLToBlob(dataURL) {
const arr = dataURL.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
END