當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js createGraphics()用法及代碼示例

p5.j​​s 中的 createGraphics() 函數用於創建 off-screen 圖形緩衝區。它創建並返回一個新的 p5.Renderer 對象。

用法:

createGraphics(w, h, [renderer])

參數:此函數接受上述和以下描述的三個參數:

  • w:它是一個設置 off-screen 圖形緩衝區寬度的數字。
  • h:它是一個設置 off-screen 圖形緩衝區高度的數字。
  • renderer:它是將模式設置為 P2D 或 WEBGL 的常量。它是一個可選參數。如果未定義,則默認為 P2D。

返回值:它返回一個包含 off-screen 圖形緩衝區的 p5.Graphics 對象。

下麵的例子說明了 p5.js 中的 createGraphics() 函數:



範例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);
}

輸出:

範例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 objcets 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);
}

輸出:

參考:https://p5js.org/reference/#/p5/createGraphics




相關用法


注:本文由純淨天空篩選整理自_sh_pallavi大神的英文原創作品 p5.js createGraphics() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。