createGraphics referencing existing canvas context

Is there an easy way to bind an existing html canvas to the Graphics object you create with createGraphics()?

Example: I have an existing painted 2D canvas that I would like to draw via image() into my existing WEBGL canvas. I just can’t find a method how I can do that other than redrawing everything within p5js. Since createGraphics generates a canvas element. There must be an easy way to just change the reference.

1 Like

I don’t know if there’s a fancy way of doing it, but you could always fall back on the underlying HTML5 Canvas API. One approach:

// Select the existing canvas (underlying HTML element via `elt`).
const existingCanvas = select('#existingCanvas').elt;

// Use native API to draw existing canvas to the p5.js canvas.
drawingContext.drawImage(existingCanvas, 0, 0);

From the reference:

The p5.js API provides a lot of functionality for creating graphics, but there is some native HTML5 Canvas functionality that is not exposed by p5. You can still call it directly using the variable drawingContext[.]

1 Like

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

What a coincidence. I was just day or two ago wondering would this be possible. You saved me a trouble of asking.

1 Like

Ahh this is soo good and helpful! needed to render p5 to an existing canvas for a project and this is the only solution that’s worked…! would be great if it could make it into the main source – once I share example of usage, i’ll (re)open an issue about how/why it’s needed.