Open In App

p5.js createGraphics() Function

Last Updated : 20 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 graphics
let 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 graphics
let 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:

Reference:https://p5js.org/reference/#/p5/createGraphics



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads