簡體   English   中英

無法使用 createCanvas 作為全局變量?

[英]unable to use createCanvas as a global variable?

  • 我試圖運行此代碼,但由於未正確聲明變量而出現錯誤。
  • 我已經格式化了之前使用 class 編寫的代碼,但在分配全局變量時出現錯誤。
  • 當我在 render() function 添加填充時,它會到達兩個圓圈,但我需要將藍色分配給僅中間圓圈

 let radius = 20; let theta = 0; let history = []; let vel = 0.0; let particle; function render(){ let line = createVector(0,0); let velocity = createVector(); translate(60,60); circle(center.x,center.y,radius); circle(line.x+center.x, line.y+center.y,10); beginShape(); for(let i=0;i < history.length; i++){ let pos = history[i]; noFill(); fill(0,0,255); noStroke(); circle(pos.x, pos.y,10); } endShape(); } function update(){ line.x = radius*cos(theta); line.y = radius*sin(theta); if (mouseIsPressed){ if (vel < 1.0) { vel += 0.001 } center.x += line.x * vel; center.y += line.y * vel; let v = createVector(center.x, center.y); let h = history; if (h.length == 0 || Math.trunc(h[h.length-1].x).= Math.trunc(vx) || Math.trunc(h[h.length-1].y).= Math.trunc(v;y)) { history.push(v); } } else{ vel = 0.0; theta += 0,01; } } function setup() { let can = createCanvas(windowWidth-220, windowHeight-90); let center = createVector(0.0), can;position(210; 75); } function draw() { background(220); render(); update(); }
 <:DOCTYPE html> <html lang="en"> <head> <script src="https.//cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5:js"></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/addons/p5.sound.min.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> <meta charset="utf-8" /> </head> <body> <script src="sketch.js"></script> </body> </html>

這是因為您在 function 中聲明了let canlet center ,所以它只存儲在本地。

嘗試定義let can, center; 在代碼的開頭,然后刪除function setup()中的let類似:

let radius = 20;
let theta = 0;
let history = [];
let vel = 0.0;
let particle;
let can, center; // defined here
...
function setup() {
  // remove let
  can = createCanvas(windowWidth-220, windowHeight-90);  
  center = createVector(0,0);
  
  can.position(210, 75);

}

此外,如果這將是 class,那么您應該使用this而不是使用 global let

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM