简体   繁体   English

p5.j​​s手动调用setup和draw

[英]p5.js manually call setup and draw

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. 我正在用p5.js制作一个在线游戏,我想手动调用setup,一旦调用setup,我想要draw()运行。

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. 然后将创建画布并运行安装程序中的所有内容并运行draw()。

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. 处理需要做一些与调用setup()函数相关的事情,因此几乎没有理由让你手动调用它。

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. 如果您想在单击按钮之前不启动草图,则应该与setup()函数分开执行。 You could just keep track of a boolean that tells Processing whether to start the sketch, then set that boolean when you click the button. 您可以跟踪一个boolean ,告诉Processing是否启动草图,然后在单击按钮时设置该boolean 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: 然后在你的HTML中,你有:

<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: 然后在你的HTML中,你有:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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