简体   繁体   中英

An “update” function for JavaScript, similar to p5.js?

I used p5.js in order to prototype some ideas, but since p5.js doesn't really draw stuff using actual HTML (as far as I understand, it uses a canvas), it doesn't include stuff like selectable text. The effect I'm trying to achieve is going to be constantly changing (The CSS of a DOM element will change constantly), is there a way that I am able to change CSS function every "frame", similar to the update function of p5.js?

Sticking with p5

If you are comfortable using p5 you can stick with that. Here is a demo from the docs on what the style() function does:

https://p5js.org/reference/#/p5.Element/style

You'll notice it uses another p5 function, createDiv() to make an html div (that you can change the contents of) which is I think itself a wrapper for JavaScript's createElement .

https://p5js.org/reference/#/p5/createDiv

Its always worth searching the docs of the library you already use before you start down learning something new in my opinion.

If p5 is just absolutely not the way you want to go (maybe you aren't using 80% of its functions) there are two other routes I mentioned in my comment.

requestAnimationFrame

requestAnimationFrame will sync with the screen's refresh rate and computer's processor to create the smoothest possible animations. This is useful for lots of animation if you want it to appear super smooth.

function animationFunction(){

  // Put your logic here:

  // this makes the function repeat again
  requestAnimationFrame(animationFunction);
}

// this "kicks it off"
requestAnimationFrame(animationFunction);

setInterval

Set interval accepts a function as the first argument and a number of milliseconds as the second, so this is better for ones where you want to explicitly set how long between "frames".

let numberOfMillisecondsBetweenEachFrame = 300;

setInterval(function(){
  // Put your logic here
}, numberOfMillisecondsBetweenEachFrame);

Here is an example of both methods:

https://codepen.io/EightArmsHQ/pen/KKdNJRx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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