Bitmap cannot be used as a mask in html5

This https://github.com/openfl/openfl/issues/1406 was marked as “Moved to “Recently Completed””.
This https://github.com/openfl/openfl/pull/1709 was marked as “Closed”.

However, a simple test of using a bitmap as a mask in html5 (openfl 8.9.6) shows nothing on the page. You can mask a bitmap with a shape, but not a shape with a bitmap.

class SimpleTestMask extends Sprite {

public function new() {
        super();

        var container:Sprite = new Sprite();
        this.addChild(container);

        var sh:Shape = new Shape();
        sh.graphics.beginFill(0xFF0000);
        sh.graphics.drawCircle(0, 0, 200);
        sh.graphics.endFill();

        var bmd:BitmapData = new Match02(0, 0);
        var bmp:Bitmap = new Bitmap(bmd);
        container.addChild(bmp);
        //container.mask = sh; // This works - bitmap is masked by shape
        container.mask = bmp; // This does not - cannot use bitmaps as masks???
    }

}

@:bitmap("../src/com/masque/samples/simple/Match02.png")
class Match02 extends BitmapData { }

FWIW - I tried both canvas and webgl compiles

2 Likes

Hi, I am having this problem as of 2022… has anyone found a way to do this?

I ended up solving this with the below function:

function drawMaskedElement(color: Color, maskBitmapData: BitmapData, app: any) {
  var square = new Sprite();
  square.graphics.beginFill(color.rgbNumber());
  square.graphics.drawRect(0, 0, maskBitmapData.width, maskBitmapData.height);
  app.addChild(square);

  var bitmap = new Bitmap(maskBitmapData);
  bitmap.blendMode = BlendMode.ERASE;
  app.addChild(bitmap);
}

EDIT
Actually the code below works better. Copyting the alpha channel of the mask to the alpha channel of the fill wasn’t working for some reason, but doing the reverse where you copy the color channels from the fill to the color channels of the mask does work

function drawMaskedElement(color: Color, maskBitmapData: BitmapData, app: any) {
  let squareBitmapData = new BitmapData(
    maskBitmapData.width,
    maskBitmapData.height,
    false,
    color.rgbNumber()
  );
  var rect: Rectangle = new Rectangle(
    0,
    0,
    maskBitmapData.width,
    maskBitmapData.height
  );
  maskBitmapData.copyChannel(
    squareBitmapData,
    rect,
    new Point(),
    BitmapDataChannel.RED,
    BitmapDataChannel.RED
  );
  maskBitmapData.copyChannel(
    squareBitmapData,
    rect,
    new Point(),
    BitmapDataChannel.GREEN,
    BitmapDataChannel.GREEN
  );
  maskBitmapData.copyChannel(
    squareBitmapData,
    rect,
    new Point(),
    BitmapDataChannel.BLUE,
    BitmapDataChannel.BLUE
  );
  let bitmap = new Bitmap(maskBitmapData);
  app.addChild(bitmap);
}