Archive

Archive for October, 2009

BlendMode.DIFFERENCE and why it’s awesome.

October 16th, 2009 alducente No comments

Straight from the CS3 Help section:

Compares the constituent colors of the display object with the colors of its background, and subtracts the darker of the values of the two constituent colors from the lighter value. This setting is commonly used for more vibrant colors.

For example, if the display object has a pixel with an RGB value of 0xFFCC33, and the background pixel has an RGB value of 0xDDF800, the resulting RGB value for the displayed pixel is 0x222C33 (because 0xFF – 0xDD = 0×22, 0xF8 – 0xCC = 0x2C, and 0×33 – 0×00 = 0×33).

So as an example, let’s say I have two Sprites, sprite “A” & sprite “B”:

difference_a_b

If I was to set sprite B’s blendMode property to BlendMode.DIFFERENCE and place it on top of sprite A, I would end up with something like this:

difference_result

So why is this useful?

Other than for creating cool visuals, we can use this feature to detect edges within any display object. So let’s pretend I used a second instance of sprite A in place of sprite B and went through the same steps, I would pretty much end up with a black box since there is no difference in pixels between the two sprites. But if I was to move that second instance of sprite A 1 pixel down and 1 pixel right, I would end up with something like this:

difference_a

Notice how only the edges of our star symbol is visible, making everything else (close to) black. Because of the gradient background we used in our sprites, there is a difference between the pixel values in the black areas when we moved our second sprite to be slightly unaligned with the first. The difference isn’t visible, but it is there. To solve this problem we can use BitmapData to “flatten” these two sprites and using the threshold() method, we can turn any pixels that have a value close to black into any color we choose, including pure black (0×000000).

Okay…now what?

Since blendMode is a property of DisplayObject, we can use it with any objects that inherit from it, including Video:

This movie requires Flash Player 9

This example uses 2 video objects in place of the 2 sprites we used in the earlier examples, we could probably increase performance by taking “snapshots” of the video and doing the same steps using 2 bitmaps instead of 2 Video instances, but I decided to keep it simple.

Using this info, we can then interact with edges extracted from the webcam to do some real-time edge detection, a cool webcam game perhaps? Or catching some snowflakes*? but I’ll save that for another post.

Over & out.

*Grant’s example was created in Flash 8(as2), which might have used a method similar to what I mentioned here, but I’m not completely sure.