javascript - 连续画布操作优化
问题描述
嗨,我制作了一个应用程序,我必须在其中操作一些 png:提取一些颜色,创建一些轮廓等......
每次我重复相同的过程:
- 等待 DOM 中的图像加载
- 创建一个具有大小的新画布
- 添加 context2D
- 绘制图像
- 获取图像数据
- 通过所有数据像素循环做一些事情
- 将新的东西 (putImageData) 放入一个空的像素数据数组中(使用 createImageData 创建)
- 将其链接到新画布
- 从此画布创建新图像
- 重复
例如:
var imgColor = new Image();
imgColor.src = this[`canvasColor${color}`].toDataURL("image/png");
// wait for load of this new color image
imgColor.onload = () => {
this[`canvasColorAndOutline${color}`].width = width;
this[`canvasColorAndOutline${color}`].height = height;
var outlineAndColorCtx = this[`canvasColorAndOutline${color}`].getContext("2d");
var dArr = [-1, -1, 0, -1, 1, -1, -1, 0, 1, 0, -1, 1, 0, 1, 1, 1], // offset array
s = this.state.outlineThickness, // thickness
i = 0, // iterator
x = 0, // final position
y = 0;
// draw images at offsets from the array scaled by s
for (; i < dArr.length; i += 2) {
outlineAndColorCtx.drawImage(imgColor, x + dArr[i] * s, y + dArr[i + 1] * s);
}
// fill with color
outlineAndColorCtx.globalCompositeOperation = "source-in";
outlineAndColorCtx.fillStyle = "YELLOW";
outlineAndColorCtx.fillRect(0, 0, width, height);
// draw original image in normal mode
outlineAndColorCtx.globalCompositeOperation = "source-over";
outlineAndColorCtx.drawImage(imgColor, x, y);
///////////////
// THIRD STEP : remove the white to keep the outline
//////////////
// create a new image with this color context to work on
var imgOutline = new Image();
imgOutline.src = this[`canvasColorAndOutline${color}`].toDataURL("image/png");
imgOutline.onload = () => {
var imageDataOutlineAndColor = outlineAndColorCtx.getImageData(0, 0, width, height)
this[`canvasOutline${color}`].width = width;
this[`canvasOutline${color}`].height = height;
const outlineCtx = this[`canvasOutline${color}`].getContext("2d");
const imageDataOutline = outlineCtx.createImageData(width, height);
for (let i = 0; i < imageDataOutlineAndColor.data.length; i += 4) {
if (
(imageDataOutlineAndColor.data[i + 0] > 100) &&
(imageDataOutlineAndColor.data[i + 1] > 100) &&
(imageDataOutlineAndColor.data[i + 2] < 5) &&
(imageDataOutlineAndColor.data[i + 3] != 0)
) {
imageDataOutline.data[i + 0] = 255;
imageDataOutline.data[i + 1] = 255;
imageDataOutline.data[i + 2] = 0;
imageDataOutline.data[i + 3] = 255;
}
}
outlineCtx.putImageData(imageDataOutline, 0, 0);
}
}
我的问题是:有没有捷径步骤7、8、9的方法来避免img.load的时间?并直接使用上下文?所以我会一直使用相同的上下文,只是在每个流程步骤中进行修改。在全球范围内,有没有办法对其进行优化?
解决方案
推荐阅读
- sql - 使用身份而不是顺序时的随机数
- maxmind - Graylog geoip 没有显示地图上的所有位置
- c# - 连接到 Redshift 集群时出错 - Npgsql.PostgresException: 28000: no pg_hba.conf entry for host
- r - remove groups with different count within a group - data.table in R
- java - 由 DateTimeFormatter 格式化为 'ne' 的时代
- git - 如何在特定提交日期之前删除 git 存储库的所有提交?
- css - 如何以 90% 的页面缩放级别编写媒体查询
- react-native - 如何在 touchableopacity 中设置焦点?
- javascript - 如何在chartjs工具提示中显示自定义数据
- c++ - 斐波那契数计算代码给出不一致的答案