javascript - 如何通过javascript识别 Canvas 中的区域

标签 javascript html design-patterns canvas image-recognition

此图像加载到 html5 Canvas 中。

如果用户按下正方形内的任何一点,我想用颜色填充该区域。但就在里面,颜色停在黑线处。您可以将填充工具想象成 Windows Paint 中的填充工具。

我该如何解决这个问题?是否有用于启动此类函数的 javascript 库?

shape

最佳答案

您要查找的内容称为 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/

相关文章:

javascript - 执行函数时页面刷新/崩溃

javascript - 值 =""在 <input ng-mode ..> 中的作用

html - 如何在 html textarea 中显示以下文本?

php - 如何使用 PHP 和 AJAX 显示 MySQL 数据库

c# - 原型(prototype)设计模式

javascript - 元素排序例程在 Firefox 中有效,但在 Chrome 中崩溃

javascript - 表单验证后启用提交按钮,如果单击提交按钮使用 jQuery 打开模式弹出窗口?

php - codeigniter 框架 php 中的外部样式表错误?

c# - 我应该为移动客户端/服务器对象使用哪种C#类模式

php - DI 是单例和/或静态对象的唯一解决方案吗?