jquery - 为什么我的 Floodfill 不能完全填充图像?
问题描述
我觉得这与像素计数有关,但是我似乎无法弄清楚如何扩展匹配以覆盖整个形状。
参见图片示例:
我在这里添加了一个运行示例:
这是洪水填充功能1:
function getPixel(imageData, x, y) {
if (x < 0 || y < 0 || x >= imageData.width || y >= imageData.height) {
return [-1, -1, -1, -1];
} else {
const offset = (y * imageData.width + x) * 4;
return imageData.data.slice(offset, offset + 4);
}
}
设置像素颜色
function setPixel(imageData, x, y, color) {
const offset = (y * imageData.width + x) * 4;
imageData.data[offset + 0] = color[0];
imageData.data[offset + 1] = color[1];
imageData.data[offset + 2] = color[2];
imageData.data[offset + 3] = color[0];
}
查找颜色函数:
function colorsMatch(a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
}
填充像素数组
function floodFill(ctx, x, y, fillColor) {
const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
const targetColor = getPixel(imageData, x, y);
if (!colorsMatch(targetColor, fillColor)) {
const pixelsToCheck = [x, y];
while (pixelsToCheck.length > 0) {
const y = pixelsToCheck.pop();
const x = pixelsToCheck.pop();
const currentColor = getPixel(imageData, x, y);
if (colorsMatch(currentColor, targetColor)) {
setPixel(imageData, x, y, fillColor);
pixelsToCheck.push(x + 1, y);
pixelsToCheck.push(x - 1, y);
pixelsToCheck.push(x, y + 1);
pixelsToCheck.push(x, y - 1);
}
}
ctx.putImageData(imageData, 0, 0);
}
}
它工作正常,但在未填充的一侧留下了几个像素,
解决方案
推荐阅读
- excel - 根据标题引用,根据同一行中另一个单元格的值清除单元格的内容
- travis-ci - 为什么在我的 Travis CI 构建中 Coverity Scan 突然停止而没有错误消息
- python-3.x - 在每次迭代训练模型时打印输入
- php - 为什么我的自定义代码在日志中显示警告?
- javascript - 如何从另一个插件访问一个 Vue 插件(使用 Vue.prototype)?
- java - java - 如何在java spring中强制文件中的内容为utf-8?
- r - 将字符列表转换为R中的命名数字
- oracle - PL/SQL - 检索输出
- nativescript - NativeScript-Vue在android下渲染RadListView很慢并冻结UI
- html - “定理”的语义正确的html标签?