有两张分辨率相同的图片,需要将图二中,与图一相交部分的颜色删掉
1、首先加载两张图片,且需要保证两张图片都要加载完成
2、封装 new Image() 方法为 Promise
loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image()
img.crossOrigin = '' // 处理跨域
img.src = src
img.onload = () => {
resolve(img)
}
img.onerror = err => {
reject(err)
}
})
}
3、使用 async await 命令同步加载图片
const imageObj1 = await this.loadImage(require("@onemap/assets/河道.png")).then()
const imageObj2 = await this.loadImage(require("@onemap/assets/村庄.png")).then()
4、使用canvas处理图片
const canvas1 = document.createElement('canvas')
const context1 = canvas1.getContext('2d')
canvas1.width = imageObj1.width
canvas1.height = imageObj1.height
context1.drawImage(imageObj1, 0, 0)
const ctx1 = canvas1.getContext('2d')
const imageData1 = ctx1.getImageData(0, 0, canvas1.width, canvas1.height)
const list1 = imageData1.data
const canvas2 = document.createElement('canvas')
const context2 = canvas2.getContext('2d')
canvas2.width = imageObj2.width
canvas2.height = imageObj2.height
context2.drawImage(imageObj2, 0, 0)
const ctx2 = canvas2.getContext('2d')
const imageData2 = ctx2.getImageData(0, 0, canvas2.width, canvas2.height)
const list2 = imageData2.data
const { width, height } = canvas1
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const index = (y * width + x) * 4
const r1 = list1[index]
const g1 = list1[index + 1]
const b1 = list1[index + 2]
const r2 = list2[index]
const g2 = list2[index + 1]
const b2 = list2[index + 2]
const a2 = list2[index + 3] // 透明度
// 判断图一有颜色的地方为图二设置为全透明
if (r1 > 0 || g1 > 0 || b1 > 0) {
list2[index] = 0
list2[index + 1] = 0
list2[index + 2] = 0
list2[index + 3] = 0
}
}
}
ctx2.putImageData(imageData2, 0, 0)
const imgUrl = canvas2.toDataURL()