首页 > 解决方案 > 为什么我的 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);
        
      }
    }

它工作正常,但在未填充的一侧留下了几个像素,

标签: jqueryimagecanvaspngflood-fill

解决方案


推荐阅读