p5.j​​s手动调用设置和绘制 [英] p5.js manually call setup and draw

查看:58
本文介绍了p5.j​​s手动调用设置和绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,如果我单击一个按钮:

For example, if I click a button:

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

然后将创建画布,并运行设置中的所有内容,并运行draw().

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

推荐答案

为什么要这样做?

处理过程需要做很多与调用setup()函数有关的事情,因此几乎没有理由让您手动调用它.

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()功能分开进行.您可以跟踪boolean,该boolean告诉Processing是否要开始绘制草图,然后在单击按钮时将其设置为boolean.像这样:

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

然后在您的html中,您将:

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

然后在您的html中,您将:

Then in your html, you'd have:

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

这篇关于p5.j​​s手动调用设置和绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆