# createGraphics referencing existing canvas context

**URL:** <https://discourse.processing.org/t/creategraphics-referencing-existing-canvas-context/21067>\
**Category:** Coding Questions\
**Created:** [May 19, 2020, 8:02pm UTC](https://discourse.processing.org/t/creategraphics-referencing-existing-canvas-context/21067 "2020-05-19T20:02:04Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![vheun](https://avatars.discourse-cdn.com/v4/letter/v/51bf81/32.png) [@vheun](https://discourse.processing.org/u/vheun)\
**Post date:** [May 19, 2020, 9:19pm UTC](https://discourse.processing.org/t/creategraphics-referencing-existing-canvas-context/21067/3 "2020-05-19T21:19:04Z")

</div>

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.

```auto
 _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.

```auto
_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:

> <https://github.com/processing/p5.js/pull/4563>

---

_[View the full topic](https://discourse.processing.org/t/creategraphics-referencing-existing-canvas-context/21067)._
