createGraphics referencing existing canvas context

I found a very simple elegant solution. I made the following changes:

A canvas element is handed over via the function call and the new Graphics instance.

 _main.default.prototype.createGraphics = function(w, h, renderer, canvas) {
            _main.default._validateParameters('createGraphics', arguments);
            return new _main.default.Graphics(w, h, renderer, this, canvas);
          };

and the Graphics constructor uses that canvas element to replace the creation of a new element.

_main.default.Graphics = function(w, h, renderer, pInst, canvas) {
            var r = renderer || constants.P2D;

            if(canvas){
                this.canvas = canvas;
            }else {
                this.canvas = document.createElement('canvas'); 
            }
           
            var node = pInst._userNode || document.body;
                if(!canvas)
            node.appendChild(this.canvas);

As a result, you can use an existing canvas element as an image buffer.
This change does not affect the usual behavior.

I created a pull request:

4 Likes