gpt4 book ai didi

javascript - 无论如何,我可以在 p5.js 中为 div 提供一个函数吗

转载 作者:行者123 更新时间:2023-12-02 16:13:55 26 4
gpt4 key购买 nike

我正在尝试使用 p5.js 获取我创建的 div 并使其每小时在屏幕上移动一次,我想知道这是否可能,我也想知道该 div 是否可以每小时随机改变颜色p5.j​​s

最佳答案

一种方法是使用 window.setInterval功能。通过这个函数,我们可以每小时执行一次动画。然而,出现的一个问题是,根据P5.js documentation, 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);

关于javascript - 无论如何,我可以在 p5.js 中为 div 提供一个函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29869910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com