有没有办法从一个点填充,直到它使用HTML Canvas和JavaScript到达边框?

Dav*_*key 6 html javascript html5 canvas

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

PAINT (200, 200), 2, 10

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

我们的想法是,人们可以使用一种颜色绘制轮廓(例如状态),然后用另一种颜色填充整个轮廓.它不会填满整个屏幕,因为轮廓是填充停止的颜色.

Joh*_*pit 3

您可以使用洪水填充来填充区域。它以起点(或种子点)作为输入,并通过尝试填充其空邻居来递归地填充该区域。

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
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

isEmpty(point)(x, y)是测试该点是否填充边界颜色(在本例中为浅绿色)的函数。

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

这些功能的实现很简单,我把它留给你。

上面的实现使用了4 个连通的邻域。但它可以轻松扩展到 6 或 8 个相连的邻域。