The createGraphics() function in p5.js is used for creating an off-screen graphics buffer. It creates and returns a new p5.Renderer object.
Syntax:
createGraphics(w, h, [renderer])
Parameter: This function accepts three parameters as mentioned above and described below:
- w: It is a number that sets the width of the off-screen graphics buffer.
- h: It is a number that sets the height of the off-screen graphics buffer.
- renderer: It is a constant that sets the mode to either P2D or WEBGL. It is an optional parameter. It defaults to P2D if undefined.
Return Value: It returns a p5.Graphics object that contains the off-screen graphics buffer.
The below example illustrates the createGraphics() function in p5.js:
Example 1:
Javascript
// Define the variable to store the graphicslet gfg;Â
function setup() {  // Set the canvas  createCanvas(600, 600, WEBGL);Â
  // Create a new graphics renderer  gfg = createGraphics(300, 300);Â
  // Change the properties of the  // graphics buffer  gfg.background(255, 100);  gfg.textSize(64);  gfg.fill("green");  gfg.textAlign(CENTER);  gfg.text("GFG", 150, 50);}Â
function draw() {Â Â background(0);Â
  // Add a point light to the scene  pointLight(255, 255, 255, 0, -200, 200);Â
  noStroke();  rotateZ(frameCount * 0.02);  rotateX(frameCount * 0.02);  noStroke();Â
  // Apply the graphics created  // as a texture  texture(gfg);Â
  // Use a box for the texture  box(150);} |
Output:
Example 2:
Javascript
// Define the variable to store the graphicslet graphics;Â
function setup() {  // Set the canvas  createCanvas(600, 600, WEBGL);Â
  // Create a new graphics renderer  graphics = createGraphics(200, 200);  graphics.background(255);}Â
function draw() {Â Â background(0);Â
  // Add the required objects to the  // graphics buffer  graphics.line(0, 0, 200, 200);  graphics.line(100, 0, 200, 200);  graphics.line(100, 200, 200, 100);     graphics.fill("green");  graphics.triangle(30, 75, 50, 20, 85, 70);Â
  ambientLight(150);Â
  // Add a point light to the scene  pointLight(255, 255, 255, 0, -200, 200);Â
  rotateZ(frameCount * 0.02);  rotateX(frameCount * 0.02);Â
  // Apply the graphics created  // as a texture  texture(graphics);Â
  // Use a box for the texture  box(150);} |
Output:

