问题背景
通过getImageData函数得到的ImageData通过putImageData重新放到canvas容器无法进行resize操作,如果通过toDataURL函数转为Image再使用drawImage函数性能太差。
解决代码
处理代码出自:https://gist.github.com/mauriciomassaia/b9e7ef6667a622b104c00249f77f8c03
// 输入imageData,resize后的长宽
async function resizeImageData(imageData, width, height) {
const resizeWidth = width >> 0
const resizeHeight = height >> 0
const ibm = await window.createImageBitmap(imageData, 0, 0, imageData.width, imageData.height, {
resizeWidth,
resizeHeight
})
const canvas = document.createElement('canvas')
canvas.width = resizeWidth
canvas.height = resizeHeight
const ctx = canvas.getContext('2d', {
willReadFrequently: true
})
// 不注释这一行, 得到的图像就会有缺失
// ctx.scale(resizeWidth / imageData.width, resizeHeight / imageData.height)
ctx.drawImage(ibm, 0, 0)
return ctx.getImageData(0, 0, resizeWidth, resizeHeight)
}
上述代码是目前性能与表现最好的方案。
调用代码
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d', { willReadFrequently: true })
// 返回的结果是一个Promise
resizeImageData(imgData, resizeWidth, resizeHeight).then(data => {
// 后面两位0, 0代表图像起始点的左上角
ctx.putImageData(data, 0, 0)
});
其他优化
使用willReadFrequently,在频繁使用getImageData的情况下可以进行提速。
MDN原文:A boolean value that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling getImageData() frequently.
const ctx = canvas.getContext('2d', { willReadFrequently: true })