有没有一种方法可以使用HTML Canvas和JavaScript从一个点填充到它到达边界

Is there a way to fill from a point till it hits a border using HTML Canvas and JavaScript?

本文关键字:填充 一个 边界 Canvas 方法 一种 可以使 有没有 HTML JavaScript      更新时间:2023-09-26

我正在使用一些旧的基本代码。它是这样的:

PAINT (200, 200), 2, 10

这基本上意味着:用深绿色填充从坐标X 200 Y 200开始的区域,直到该点达到浅绿色的边界颜色,然后停止填充。

这个想法是,可以用一种颜色绘制一个轮廓(比如一个状态),然后用另一种颜色填充整个轮廓。它不会填充整个屏幕,因为轮廓是填充停止时的颜色。

您可以使用整体填充来填充区域。它以一个起始点(或种子点)作为输入,并通过尝试填充其空邻居来递归填充区域。

JavaScript中一个简单的基于堆栈的实现:

// Takes the seed point as input
var floodfill = function(point) {
    var stack = Array();
    stack.push(point); // Push the seed
    while(stack.length > 0) {
        var currPoint = stack.pop();
        if(isEmpty(currPoint)) { // Check if the point is not filled
            setPixel(currPoint); // Fill the point with the foreground
            stack.push(currPoint.x + 1, currPoint.y); // Fill the east neighbour
            stack.push(currPoint.x, currPoint.y + 1); // Fill the south neighbour
            stack.push(currPoint.x - 1, currPoint.y); // Fill the west neighbour
            stack.push(currPoint.x, currPoint.y - 1); // Fill the north neighbour
        }
    }
};

isEmpty(point)是测试点(x, y)是否填充有边界颜色(在这种情况下为浅绿色)的函数。

setPixel(point)使用前景色(在您的情况下为深绿色)填充点(x, y)

这些函数的实现是琐碎的,我把它留给您。

上面的实现使用了一个4连通邻域。但它可以很容易地扩展到6或8个连接的社区。