如果有这么一个需求:把多张图片按顺序拼接成一张长图并输出。那么你看这里就对了。
长图拼接主要是利用canvas的drawImage方法,一张张把现有的图片往画布上画出来,具体的drawImage使用方法请自行查找。
filesToInstances(files) {
const length = files.length
const instances = []
let finished = 0
files.forEach((file, index) => {
const image = new Image()
image.src = file.viewUrl
image.setAttribute('crossOrigin', 'anonymous')
image.onload = () => {
// 图片实例化成功后存起来
instances[index] = image
finished++
if (finished === length) {
this.drawImages(instances)
}
}
})
},
drawImages(images) {
const width = this.widths
const heights = images.map(item => (width / item.width) * item.height)
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = heights.reduce((total, current) => total + current)
const context = canvas.getContext('2d')
let y = 0
images.forEach((item, index) => {
const height = heights[index]
context.drawImage(item, 0, y, width, height)
y += height
})
const base64Url = canvas.toDataURL('image/jpeg', this.quality)
this.dealImages(base64Url)
// if (this.returnType == "base64" && this.isAutoDownload) {
// this.downloadFile(this.createFileName(), base64Url);
// }
}