Open In App

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:

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:




// 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:




// 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


Article Tags :