简体   繁体   中英

unable to use createCanvas as a global variable?

  • I was trying to run this code but I am getting error for not declaring variables properly.
  • I have formatted this code which is previously written using a class but I am getting errors in assigning global variables.
  • When I am adding fill in render() function it is getting to both circles but i need to assign blue to only middle circle

 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>

It is because you are declaring let can and let center inside a function, so it's only stored locally.

Try defining let can, center; at the beginning of your code, and then removing the let s inside function setup() Something like:

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);

}

Also, if this is going to be a class, then instead of using global let s you should use this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM