禁用黑色像素绘图

时间:2014-07-03 07:06:48

标签: javascript fabricjs

我有一个fabric.js画布,其中包含一个像这样的图像对象: enter image description here

我可以使用多种颜色/画笔绘制该图像,但我想要绘制黑色线条/像素。这是因为它描述了我的图像上的墙壁。

所以,如果我,例如在画布上画一些红色,它应该是这样的:

enter image description here

如您所见,黑线应该持续存在。但最大的问题是:我如何在fabric.js中做到这一点?

我可以想到两个解决方案:

  1. 在您绘制的fabric.js代码中找到该位置。添加一个检查是否(this_pixel_is_black){不做任何事情}其他{绘制像素..}
  2. 创建一个(PHP)脚本,遍历源图像的每个像素。如果它是黑色像素,则会在新的透明画布上绘制。保存该图像,并将其添加到另一个fabric.js图像之上。然后,当用户绘制时,它应该将它绘制在顶部的透明画布下面。
  3. 你有更好的想法吗?而且我不知道如何落实我的两条建议。

1 个答案:

答案 0 :(得分:1)

我在OP中使用建议2解决了这个问题。

查看了fabric.js源代码并注意到绘制后在mouseUp上触发的方法_finalizeAndAddPath。该方法会触发事件path:created

在制作fabric.js画布时,我首先创建"背景"图像,然后我(通过PHP脚本)创建一个只填充黑色像素的透明图像。

当抛出path:created事件时,我向后移动绘制的路径,因此透明层仍位于顶部。它实际上真的很棒!

你可以在这里看到一个有效的JSFiddle:http://jsfiddle.net/2u4h4/

如果有人对PHP脚本感兴趣,该脚本会将图像转换为仅包含黑色像素的透明png,那么就在这里:

$img = imagecreatefrompng('source.png');
$width = imagesx($img);
$height = imagesy($img);

//Placeholder to transparent image
$img_transp = imagecreatetruecolor($width, $height);

//Make image transparent (on white)
$index = imagecolorexact($img_transp, 255, 255, 255); 
imagecolortransparent($img_transp, $index); 
imagefill($img_transp, 0, 0, $index);

$black = imagecolorallocate($img_transp, 0, 0, 0);

//Loop every pixel
for($x = 0;$x < $width;$x++){
    for($y = 0;$y < $height;$y++){
        if(imagecolorat($img, $x, $y) == 0){ //Is the pixel black?
            imagesetpixel($img_transp, $x, $y, $black); //Draw the black pixel
        }
    }
}

header('Content-Type: image/png');
imagepng($img_transp); //Show the image to the user
相关问题