Saturday, October 25, 2025
HomeLanguagesJavascriptp5.js createGraphics() Function

p5.js createGraphics() Function

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

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS