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


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

p5.j​​s中的vertex()函數用於指定用於繪製形狀的頂點的坐標。它隻能與beginShape()和endShape()函數一起使用,以製作各種形狀和曲線,例如點,線,三角形,四邊形和多邊形。

用法:

vertex( x, y )

OR

vertex( x, y, z, [u], [v] )

參數:該函數接受上述和以下所述的五個參數:

  • x:它是一個數字,用於指定頂點的x坐標。
  • y:它是一個數字,用於指定頂點的y坐標。
  • z:它是一個數字,用於指定頂點的z坐標。
  • u:它是一個數字,指定頂點紋理的u-coordinate。它是一個可選參數。
  • v:它是一個數字,指定頂點紋理的v-coordinate。它是一個可選參數。

以下示例說明了p5.js中的vertex()函數:



範例1:

let currMode; 
  
function setup() { 
  createCanvas(400, 300); 
  textSize(18); 
  
  let shapeModes = [LINES, TRIANGLES, TRIANGLE_FAN,  
                    TRIANGLE_STRIP, QUADS]; 
  let index = 0; 
  currMode = shapeModes[index]; 
  
  let helpText = createP( 
    `Click on the button to change the shape drawing mode. 
    The red circles represent the vertices of the shape` 
  ); 
  helpText.position(20, 0); 
  
  let closeBtn = createButton("Change mode"); 
  closeBtn.position(20, 60); 
  closeBtn.mouseClicked(() => { 
    if (index < shapeModes.length) index++; 
    else index = 0; 
    currMode = shapeModes[index]; 
  }); 
} 
  
function draw() { 
  clear(); 
  
  // Starting the shape using beginShape() 
  beginShape(currMode); 
  
  // Specifying all the vertices 
  vertex(145, 245); 
  vertex(50, 105); 
  vertex(25, 235); 
  vertex(115, 120); 
  vertex(250, 125); 
  
  // Ending the shape using endShape() 
  endShape(); 
  
  // Points for demonstration 
  fill("red"); 
  circle(145, 245, 10); 
  circle(50, 105, 10); 
  circle(25, 235, 10); 
  circle(115, 120, 10); 
  circle(250, 125, 10); 
  noFill(); 
}

輸出:

vertex-changeModes

範例2:

let vertices = []; 
  
function setup() { 
  createCanvas(400, 300); 
  textSize(18); 
  text("Click anywhere to place a vertice "+ 
       "at that point", 10, 20); 
} 
  
function mouseClicked() { 
  // Update the vertices array with 
  // current mouse position 
  vertices.push({ x:mouseX, y:mouseY }); 
  
  clear(); 
  fill("black"); 
  text("Click anywhere to place a vertice "+ 
       "at that point", 10, 20); 
  
  noFill(); 
  
  // Draw shape using the current vertices array 
  beginShape(); 
  for (let i = 0; i < vertices.length; i++) 
    vertex(vertices[i].x, vertices[i].y); 
  endShape(CLOSE); 
  
  fill("red"); 
  // Draw a circle at all the vertices 
  for (let i = 0; i < vertices.length; i++) 
    circle(vertices[i].x, vertices[i].y, 15); 
}

輸出:

vertex-placePoint

在線編輯: https://editor.p5js.org/

環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

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




相關用法


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