[英]unable to use createCanvas as a global variable?
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 can
和let 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.