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


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

p5.j​​s中的camera()函數用於設置虛擬相機在3D草圖上的位置。這可用於模擬攝像機在場景中移動時的位置,從而可以從各種角度查看對象。

此函數的參數包括設置攝像機的位置,攝像機的中心以及指向上方的矢量。

用法:

camera([x], [y], [z], [centerX], [centerY], [centerZ],
            [upX], [upY], [upZ])

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

  • x:該數字表示攝像機在x軸上的位置。
  • y:該數字表示攝像機在y軸上的位置。
  • z:該數字表示相機在z軸上的位置。
  • centerX:這是一個數字,表示草圖中心的x坐標。
  • centerY:這是一個數字,表示草圖中心的y坐標。
  • centerZ:這是一個數字,表示草圖中心的z坐標。
  • upX:這是一個數字,表示相機發出的方向‘up’的x分量。
  • upY:這是一個數字,表示相機發出的方向‘up’的y分量。
  • upZ:這是一個數字,表示相機發出的方向‘up’的z分量。

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



範例1:設置相機在x軸上的視圖。

Javascript

function setup() { 
    
  createCanvas(600, 400, WEBGL); 
} 
  
function draw() { 
    
  background(175); 
    
  // Map the coordinates of the mouse 
  // to the variable 
  let cX = map(mouseX, 0, 
               width, -200, 200); 
    
  // Set the camera to the given coordinates 
  camera(cX, 0, (height/2) / tan(PI/6), 
         cX, 0, 0, 0, 1, 0); 
    
  ambientLight(255); 
    
  rotateZ(frameCount * 0.01); 
  rotateX(frameCount * 0.03); 
  rotateY(frameCount * 0.06); 
  noStroke(); 
  normalMaterial(); 
    
  box(100, 100, 100); 
}

輸出:

範例2:每幀以隨機方向設置攝像機的視圖。

Javascript

function setup() { 
    
  frameRate(5); 
  createCanvas(600, 400, WEBGL); 
} 
  
function draw() { 
    
  background(175); 
    
  let cX = random(-10,10); 
  let cY = random(-10,10); 
  let cZ = random(-10,10); 
    
  camera(cX, cY, 
         cZ+(height/2) / tan(PI/6), 
         cX, 0, 0, 0, 1, 0); 
    
  ambientLight(255); 
    
  rotateX(frameCount * 0.1); 
  rotateY(frameCount * 0.1); 
    
  noStroke(); 
  normalMaterial(); 
    
  box(100, 100, 100); 
}

輸出:


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

相關用法


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