I just finished a project that allowed a user to dynamically draw lines on a chalkboard. Obviously, I used the Flash drawing API to draw the lines, but I wanted to give the lines a chalk texture. I figured it would be simple – just create a background texture that looked like chalk and use the dynamically drawn lines as a mask…

Wrong! Flash can’t use dynamically drawn lines as a mask. It can use dynamically drawn shapes (like circles and rectangles) without a problem as long as they have a fill color. Unfortunately, Flash considers all lines to be infinitely thin vectors, so they don’t work as a mask. Even if you set the lineStyle property to be really wide, Flash simply can’t use the lines to create a mask.

I figured out a relatively easy way to do this. Check out the example below:

How is this done? Essentially, you can get around Flash's issues by creating a transparent bitmap copy of your dynamically drawn lines and then using the bitmap as your mask. Do this on every frame and you have a dynamic mask using the drawing API! Of course, with Flash, there is always a catch. The catches are:

  • You must set the BitmapData properties correctly to create a transparent bitmap (download the example and check it out)
  • You must set cacheAsBitmap to true for both the new mask and the masked object or this doesn't work.

As always, I've included a source file download. I commented this one VERY thoroughly, so you should be able to implement it pretty easily. You can toggle the "enableMasking" property in the code to see the line drawing without the masking. Combine this with my earlier post on drawing smooth lines and you can make something really cool. Good Luck!