2

Is it possible to get the CanvasRenderingContext2D at a sprite level instead of the whole canvas? Has anyone tried to have access for it? any idea?

I tried:

child.addEventListener(RenderEvent.RENDER_CANVAS, function(event)
        {
            var renderer:openfl.display.DisplayObjectRenderer = event.renderer;         
            var ctx:CanvasRenderingContext2D = renderer.context;
            ctx.shadowBlur = 20;
            ctx.shadowColor = "black";
        });

However, I am getting error:

openfl.display.DisplayObjectRenderer has no field context

How would I access the sprite’s CanvasRenderingContext2D ?

simo
  • 23,342
  • 38
  • 121
  • 218
  • What type is `child`? Is it possible to promote `event.renderer` to a `CanvasRenderer` or one of the other types that extend `DisplayObjectRenderer`? It looks like only the types that extend `DisplayObjectRenderer` have access to a rendering context. – gabriel.hayes Nov 20 '19 at 14:32
  • `child` is Sprite type – simo Nov 21 '19 at 15:13
  • Can you just cast `renderer` to a `CanvasRenderer`? I'm sure it was probably downcast from a `CanvasRenderer` to fit the definition of `RenderEvent`. – gabriel.hayes Nov 21 '19 at 21:37

1 Answers1

2

Try this casting the renderer to a CanvasRenderer:


child.addEventListener(RenderEvent.RENDER_CANVAS, function(event)
        {
            var renderer:openfl.display.CanvasRenderer = cast(event.renderer);         
            var ctx:CanvasRenderingContext2D = renderer.context;
            ctx.shadowBlur = 20;
            ctx.shadowColor = "black";
        });
gabriel.hayes
  • 2,267
  • 12
  • 15
  • Thanks! that has worked, but I've noticed that `shadowBlur ` was applied on all sprites, although I only added the event listener to a particular child – simo Nov 22 '19 at 06:11
  • Well, the context is shared by all sprites being rendered in the canvas. I'm not totally sure if OpenFL exposes something to augment sprite instances (although, I'm sure it has to be possible. Seems a pretty common task, I'd check the documentation) – gabriel.hayes Nov 22 '19 at 18:12
  • Thanks, it would be awesome to apply effects at Sprite level – simo Nov 22 '19 at 18:33