Search code examples
html5-canvashaxeopenflhaxeflixel

Access sprites in Canvas?


Targeting HTML5 in OpenFL is easy, however, I could not add glowing effects to sprites, I am thinking of a work around, that is using JavaScript library to add webGL effects to the sprites in Canvas.

But, the question is, how would I access the sprites inCanvas using JavaScript? and what tool to use to inspect sprites in Canvas ?


Solution

  • First of, since version 4.0 openfl uses webgl renderer by default and adding glow effect in that case requires a 'deep dive' into openfl/lime source code and i can't give you that. But if that's suitable for you, force openfl to use canvas fallback with

    <haxedef name="canvas"/>
    

    and then you can create custom Bitmap class (for example) with glow effect like so

    import openfl.display.Bitmap;
    import openfl.display.BitmapData;
    import openfl.display.PixelSnapping;
    import openfl._internal.renderer.cairo.CairoBitmap;
    import openfl._internal.renderer.canvas.CanvasBitmap;
    import openfl._internal.renderer.dom.DOMBitmap;
    import openfl._internal.renderer.opengl.GLBitmap;
    import openfl._internal.renderer.RenderSession;
    
    class HackyBitmap extends Bitmap
    {
    
        /**
         * Custom property for tweening
         */
        public var glowBlur:Float = 0.0;    
    
        public function new(bitmapData:BitmapData=null, pixelSnapping:PixelSnapping=null, smoothing:Bool=false) 
        {
            super(bitmapData, pixelSnapping, smoothing);
    
        }
    
    
        public override function __renderCanvas (renderSession:RenderSession):Void {
    
    
            var context = renderSession.context;
    
            if (glowBlur > 0)
            {
                context.save();
                context.shadowBlur = glowBlur;
                context.shadowColor = "white";
            }
    
    
            CanvasBitmap.render (this, renderSession);
    
            if (glowBlur > 0)
            {
                context.restore();  
            }
    
        }
    
    }
    

    Usage

    var data = Assets.getBitmapData("img/berry.png");
    var hacky = new HackyBitmap(data);
    hacky.x = hacky.y = 20;
    addChild(hacky);
    
    //to animate glow property
    Actuate.tween(hacky, 1.0, { glowBlur: 50 }).repeat().reflect();
    

    OpenFL/Lime versions

    lime 3.2.0
    openfl 4.2.0
    

    How it looks

    regular vs glowy