繁体   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