Search code examples
canvasalphacreatejseaseljs

Weird fill + stroke alpha in CreateJS


I'm attempting to create a text shadow in CreateJS, although I suspect this issue applies to any fill + stroke combination with an alpha < 1.

I want my text stroke to be aligned outside of my text, so rather than simply give my text a stroke, I've created a duplicate of the text with a stroke width twice what I need and then I put that below my "filled" text. This gives me what I want. So far so good.

For the shadow, I want to do the same thing, so I created a Container and put similar text objects inside that container, with a black fill and stroke. I then made the Container's alpha 0.5. Instead of a single "chunky" text entity of 50% black, however, I can clearly see the stroke and fill overlaid on top of one another as though they are separate entities:

enter image description here

does anyone have any pointers as to how I can work around this please?

Thanks so much for any help!

Codepen: https://codepen.io/GeorgeMooWoof/pen/BaGrovV


Solution

  • The problem is that alpha is applied to each element separately, and your stroke and text elements are separate. This results in them getting "added" together. What you can do however is cache the container first as a bitmap, and then drop the alpha of the resulting bitmap to .5, since the bitmap is a flattened version of txtShadow.

    So, just add this code right before txtShadow.alpha = .5 ...

    txtShadow.cache(txtShadowStroke.x, txtShadowStroke.y,  txtShadowStroke.getMeasuredWidth(), txtShadowStroke.getMeasuredHeight(), 2);
    

    ...which turns txtShadow's display object into a bitmap. The last param, 2, is for quality of bitmap conversion. Higher is better quality. You can undo this later if needed by calling txtShadow.uncache().

    Note that I'm having to offset the cache x and y by the position of the txtShadowStroke (first to params of .cache(x, y, w, h, quality)). Consider instead using the origin of the container (txtShadow in this case) for its children rather than the origin of the page. It will make things like this less dependent on the overall layout of the page.