p5.js manually call setup and draw

删除回忆录丶 提交于 2020-01-13 04:12:12

问题


I am making an online game with p5.js and I would like to manually call setup, and once setup is called I want draw() to run.

For example, if I click a button:

<button id="somebutton" onclick="setup()">CLICK ME!!!</button>

Then the canvas will be created and all of the stuff in setup will be run and draw() will run.


回答1:


Why do you want to do this?

Processing needs to do a bunch of things related to calling the setup() function, so there's almost never a good reason for you to call it manually.

Using a Variable

If you want to not start your sketch until you click a button, you should do that separately from the setup() function. You could keep track of a boolean that tells Processing whether to start the sketch, then set that boolean when you click the button. Something like this:

var started = false;

function setup(){
   createCanvas(windowWidth, windowHeight);
   noLoop();
}

function draw(){
   if(started){
      //your code here
   }
}

function start(){
   started = true;
   loop();
}

Then in your html, you'd have:

<button id="somebutton" onclick="start()">CLICK ME!!!</button>

Using Instance Mode

You could also use instance mode to delay the creation of your sketch. Something like this:

function startSketch(){
   var sketch = function( p ) {

     var x = 100; 
     var y = 100;

     p.setup = function() {
       p.createCanvas(700, 410);
     };

     p.draw = function() {
       p.background(0);
       p.fill(255);
       p.rect(x,y,50,50);
     };
   };

   var myp5 = new p5(sketch);
}

Then in your html, you'd have:

<button id="somebutton" onclick="startSketch()">CLICK ME!!!</button>


来源:https://stackoverflow.com/questions/39711941/p5-js-manually-call-setup-and-draw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!