“桶填充” JavaScript或coffeescript中的算法 [英] "Bucket Fill" algorithm in Javascript or coffeescript

查看:138
本文介绍了“桶填充” JavaScript或coffeescript中的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个小的coffeescript / js应用程序,允许用户设计图标(16x16像素或32X32像素)。
该图标实际上是一个具有颜色单元格的二维数组。一个单元格可以有一个颜色或为空。



我希望用户能够用bucket paint工具填充空白单元格。



这意味着




  • 如果用户点击一个空白单元格,如果用户点击了彩色单元格,则所有单元格都将以选中的颜色填充,直到到达彩色单元格


  • <




应用程序已允许用户使用所选颜色逐个填充单元格,或使用钢笔工具删除彩色单元格。



有任何建议吗?



(ps:我不使用html画布绘制)

解决方案

由于这只是16x16或32x32,您可以使用递归解决方案:



假设您的起点是将像素x / y从颜色A更改为颜色B A或B可以为空。)



在伪代码中:

  function floodfill(x,y,A,B){
if((x< 0)||(x> 15)||(y< 0)||
if(get_color(x,y)!= A)return;
set_color(x,y,B);
floodfill(x-1,y-1,A,B);
Floodfill(x-1,y,A,B);
floodfill(x-1,y + 1,A,B);
floodfill(x,y-1,A,B);
floodfill(x,y + 1,A,B);
floodfill(x + 1,y-1,A,B);
floodfill(x + 1,y,A,B);
floodfill(x + 1,y + 1,A,B);
}


i'm writing a little coffeescript/js app that allows user to design icons ( 16x16 pixels or 32X32 pixels ). The icon is actually a 2 dimensional array with color cells. A cell can have a color or be empty.

I want the user to be able to fill blank cells with a "bucket paint" tool.

It means that

  • if the user clicks on a blank cell , all the cells that are blank next to the clicked cell with be filled with the choosen color , until it reaches a colored cell

  • if the user clicks on a colored cell , all the cells that are next to the clicked cell and share the same color will be filled , but not the blank ones nor the colored ones ( with another color ).

The app already allows the user to fill cells one by one with a chosen color , or delete colored cells with a pen tool.

Any suggestions ?

(ps : i'm not using html canvas to draw )

解决方案

Since this is only 16x16 or 32x32 you can use a recursive solution:

Say your starting point is to change pixel x/y from color A to color B (A or B can be empty).

In pseudo code:

function floodfill(x,y,A,B) {
  if ((x<0) || (x>15) || (y<0) || (y>15)) return;
  if (get_color(x,y)!=A) return;
  set_color(x,y,B);
  floodfill(x-1,y-1,A,B);
  floodfill(x-1,y,A,B);
  floodfill(x-1,y+1,A,B);
  floodfill(x,y-1,A,B);
  floodfill(x,y+1,A,B);
  floodfill(x+1,y-1,A,B);
  floodfill(x+1,y,A,B);
  floodfill(x+1,y+1,A,B);
}

这篇关于“桶填充” JavaScript或coffeescript中的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆