此图像加载到 html5 Canvas 中。
如果用户按下正方形内的任何一点,我想用颜色填充该区域。但就在里面,颜色停在黑线处。您可以将填充工具想象成 Windows Paint 中的填充工具。
我该如何解决这个问题?是否有用于启动此类函数的 javascript 库?
最佳答案
您要查找的内容称为 flood fill algorithm 。这基本上会将您单击的像素的颜色作为种子。它将检查连接到种子像素且具有与种子颜色相同的所有像素,并将它们填充为所需的颜色。该算法有两种类型:8 向和 4 向。邻居定义如下(S = 种子,X = 连接):
4向
----------------
| | X | |
----------------
| X | S | X |
----------------
| | X | |
----------------
8向
----------------
| X | X | X |
----------------
| X | S | X |
----------------
| X | X | X |
----------------
递归算法如下(来自维基百科):
Flood-fill (node, target-color, replacement-color):
1. If target-color is equal to replacement-color, return.
2. If the color of node is not equal to target-color, return.
3. Set the color of node to replacement-color.
4. Perform Flood-fill (one step to the west of node, target-color, replacement-color).
Perform Flood-fill (one step to the east of node, target-color, replacement-color).
Perform Flood-fill (one step to the north of node, target-color, replacement-color).
Perform Flood-fill (one step to the south of node, target-color, replacement-color).
5. Return.
关于javascript - 如何通过javascript识别 Canvas 中的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28955110/