p5.js手动调用设置和绘制 [英] p5.js manually call setup and draw
问题描述
我正在使用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.js手动调用设置和绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!