Skip to content
Advertisement

P5 try to factorize Graphics and Canvas code

I want to factorize code for drawing same thing in a graphics or in the standard canvas.
( In my real program, i want to have autonomous class that draw themselves in some context given at construction time )
I cannot find some equivalent from canvas that can match graphics instructions except line.
In the following, i try to give either a canvas or a graphics object to the drawing method someDraw , but only line appears on canvas, while whole drawing appears in graphics.

JavaScript

You can see the (red) line drawn in canvas but not the rect or the ellipse. The graphics is correct. enter image description here

Another effect: if this small prog loops ( see noLoop() in setup ), the graphics appears fleeting first time then is no more displayed.

So, canvas and graphics are not in the same hierarchy, but is there a common way to draw on both without duplicating all code ?

Advertisement

Answer

Use Instantiation:

JavaScript

Pass either the p5 instance to someDraw

JavaScript

or the p5.Renderer object:

JavaScript

Complete example:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement