我是否可以在p5.js中为div提供一个函数



我试图使用p5.js来获取我创建的div,并使其每小时在屏幕上移动一次。我想知道这是否可能。我还想知道这个div是否可以在p5.js 中每小时随机更改颜色

实现这一点的一种方法是使用window.setInterval函数。有了这个功能,我们可以每小时执行一次动画。然而,出现的一个问题是,根据P5.js文档,draw()函数在调用setup()函数后连续执行。我们可以利用noLoop()loop函数来解决这个问题。

noLoop()函数调用将停止draw()函数的执行,而loop()函数将再次开始执行。所以,让我们来看看我们如何对其进行编码:

注意:根据文档,每个草图只能有一个绘制函数。因此,如果你在一个小时内有其他东西在动画中,这种方法可能不是最好的选择。

//stores the position of the element on the x-axis of the screen
var xPos = 0;
var delay = 60000 * 60; //1,000 milliseconds in a second
window.setInterval(function(){
//code to be called every hour; make draw function loop
loop();
}, delay);
function setup(){
//create your canvas or div or whatever
createCanvas(400, 400);
}
function draw(){
// clear the current background
background(255);
// set the fill color of your element
fill(255, 0, 0);
//change the x position so it can move across the screen
xPos = xPos + 1;
// if the circle moves off screen, it's finished animating for the hour
if(xpos > width)
{
xPos = 0; //reset back to 0;
noLoop(); //end the looping of the draw function        
}
//draw your element to the correct location and size; here I'll use an ellipse
ellipse(xPos, 100, 25, 25);
}

正如我所说的,我对P5.js不是最熟悉的,但希望这能给你足够的想法,让它发挥作用。

编辑:另一种方法是使用CSS动画。有了CSS动画,你甚至不需要P5.js就能获得你想要的效果。

HTML:

<div id="my-div" class="my-div"></div>

CSS:

.my-div {
/* animation name followed by how long the animation takes to perform */
/* browser prefixes for more browser support */
animation: slide-across-screen 1s;
-webkit-animation: slide-across-screen 1s;
-moz-animation: slide-across-screen 1s;
}
@keyframes slide-across-screen {
0% {
margin-left: 0;
}
100% {
margin-left: 100%;
}
}

JavaScript:

var div = document.getElementById("my-div");
div.addEventListener("animationend", function(){
div.style.marginLeft = 0;
div.style.animationPlayState = paused;
}
window.setInterval(function(){
div.style.animationPlayState = running; //might need browser prefixes here as well
}, 60000 * 60);

您还可以使用p5.dom.js插件库中的createDiv()元素。http://p5js.org/reference/#/libraries/p5.dom

var x = 0;
var myDiv;
function setup() {
var myDiv = createDiv("This is my DIV!");
setInterval(function() {
x+=100;
myDiv.position(x, 200);
}, 60*60*1000);
}

最新更新