Search code examples
javascriptclassextendcreatejs

Extending JavaScript Classes for use on Canvas


I am working on a project to help me gain a better understanding of JavaScript and building applications with it. I am currently making a game utilizing createjs. I'd like to extend the Shape "class" by adding some additional methods to it but can't seem to get my head around the issue.

I am not getting any runtime errors by this approach, however I think it's failing silently at a particular point.

My Subclass:

ShipGFX.prototype = new createjs.Shape();
    function ShipGFX()
    {
        createjs.Shape.apply( this );

        this.draw = function()
        {
            var g = this.graphics;

            g.clear();
            g.setStrokeStyle( 1 );
            g.beginStroke( createjs.Graphics.getRGB( 0x00ff00 ) );
            g.beginFill( createjs.Graphics.getRGB( 0x00ff00, 0.5 ) );
            g.moveTo( 0, 0 );
            g.lineTo( -5, -5 );
            g.lineTo( 10, 0 );
            g.lineTo( -5, 5 );
            g.lineTo( 0, 0 );
            g.endFill();
        }
    }

Where it's used:

var shape = new ShipGFX();
shape.draw();

So the console logs no errors and I can even log via the draw command. I think the issue is scope of this.graphics even though it doesn't fail there either. Is it a matter of scope? Is the this.graphics a reference to the prototype instance (if I understand that correctly). I'd ideally like to use Class-js as I have a better understanding of how it works but I can't even get this way to work.

Any input would be great. Thank you.


Solution

  • The reason why this was failing silently was because little did I realize that the draw function was preexisting in the createjs.Shape APIs. Changing the name to "render" solved my issue.