CappedAnimationFrames class and draw example

A simple requestAnimationFrame() example that runs at a given maximum frame rate. This sample also demonstrates using an "update" function in your code that will update the visual elements based on the amount of time passed since the last update.

by zachreynolds

HTML

<p style="color: #999; font-size: 12px;">
Depending on your computer, the <i>actual</i> FPS may be lower than the max you set.<br />
requestAnimationFrame() will typically not run faster than 60fps.
</p>
<canvas id="drawing"></canvas><br />
FPS Cap: <input type="text" id="fpsInput" value="0" disabled /><button id="startStop">Stop</button><span style="color: #999">(0 for uncapped)</span><br />
<span id="errorText" style="font-size: 12px; color: red; display: none;"></span>

<div id="particles-js" >

<script>

//<![CDATA[
window.onpageshow=function(){
/* -----------------------------------------------
/* Author : Vincent Garreau  - vincentgarreau.com
/* MIT license: https://opensource.org/licenses/MIT
/* GitHub : https://github.com/VincentGarreau/particles.js
/* How to use? : Check the GitHub README
/* v1.0.3
/* ----------------------------------------------- */
function launchParticlesJS(a,e){var i=document.querySelector("#"+a+" > canvas");pJS={canvas:{el:i,w:i.offsetWidth,h:i.offsetHeight},particles:{color:"#fff",shape:"circle",opacity:1,size:2.5,size_random:true,nb:200,line_linked:{enable_auto:true,distance:100,color:"#fff",opacity:1,width:1,condensed_mode:{enable:true,rotateX:65000,rotateY:65000}},anim:{enable:true,speed:1},array:[]},interactivity:{enable:true,mouse:{distance:100},detect_on:"canvas",mode:"grab",line_linked:{opacity:1},events:{onclick:{enable:true,mode:"push",nb:4}}},retina_detect:false,fn:{vendors:{interactivity:{}}}};if(e){if(e.particles){var b=e.particles;if(b.color){pJS.particles.color=b.color}if(b.shape){pJS.particles.shape=b.shape}if(b.opacity){pJS.particles.opacity=b.opacity}if(b.size){pJS.particles.size=b.size}if(b.size_random==false){pJS.particles.size_random=b.size_random}if(b.nb){pJS.particles.nb=b.nb}if(b.line_linked){var...

CSS

*
{
  font-family: Arial;
}

#drawing
{
  border: solid 1px black;
}

JavaScript

/***
  CappedAnimationFrames(func[, fps = 0])
  desc: This class wraps up the boilerplate code for using the window.requestAnimationFrame() function
        with an easy interface and provides the ability to throttle the framerate.
    func  - The function that will be run every frame
    fps   - The FPS cap desired (0 or blank for uncapped)
    
  .start([fps])
  desc: Begins the requests for animation frames at the set framerate
    fps    - The frame rate at which to start. Otherwise stays the same.
    
  .stop()
  desc: Stops requesting animation frames.
  
  .setFPS(fps)
  desc: Sets a new framerate at which to run. Can be set WHILE running.
    fps      - The frame rate at which the CappedAnimationFrames instance should run
    
  .isRunning()
  desc: returns the current running state of the CappedAnimationFrames instance
***/
function CappedAnimationFrames(func, fps)
{
  var maxFPS = typeof fps !== 'undefined' ? fps : 0;
  var fn = func; // The function that will be run every frame. Has a delta parameter for time difference in ms
  
  // If a function is not provided, throw an error.
  if (typeof fn === 'undefined')
    throw "CappedAnimationFrames constructor: You must provide a function to be executed.";
  
  var running = false;
  
  var requestId = null;     // The requestId. Used for cancelling this specific request.
  var tickNow = null;       // The time now in ms.
  var tickThen = null;      // The last tick time in ms.
  var tickDelta = null;     // The difference between tickNow and tickThen.
  var tickInterval = null;  // The length of each frame in ms. (calculated from maxFPS)
  
  // if the maxFPS is 0 (or less), then don't cap the framerate
  if (maxFPS <= 0)
    tickInterval = 0;
  // else, set the tickInterval to the length of each frame in ms.
  else
    tickInterval = 2000 / maxFPS;
  
  // The guts of the class. It calls the requestAnimationFrame function at the rate specified.
  function tick()
  {
    // schedule the next tick call.
 ...