Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Jul 2018
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Apply easing function to canvas requestanimationframe

    Hi all,

    I found a html canvas/javascript animation that I really want to use... a starfield warp effect. The original code uses the mouse to control speed and the warp effect but since that isn't what I want I've managed to rewrite the code to play when the window loads.

    However, I would like the stars to transition from zero velocity, speed up (warp) and then slow down to zero velocity. The functions were originally taken care of, as said, via mouse controls. I just can't figure out how to apply the same thing to functions that will do it automatically when the canvas loads.

    I know I need ease-in-out. I've looked at various easing equations but I simply don't know how and where they are meant to go in the script. Lots of tutorials out there but for very simple animations.

    I've been banging my head against the wall for the last 2 weeks trying to figure this out.

    I'd so appreciate any help.

    Here's the script...

    Code:
    <!doctype html>
    <html>
    	<head>
    	   <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=0;" />
    		<title>Warp Starfield</title>
    		
        <style type='text/css'>
     .container {background-color: #000;margin-top:0px; height: auto; width:100%;margin-left:auto;margin-right:auto;max-width:1300px;}
    
    </style>
    	</head>
    	<body>
    	   <div class = "container"> 
    
    		<canvas id="c" width="1280" height="720"></canvas>
            </div>
    
            
    <script>
    
    
    window.requestAnimFrame = (function()
    {
       return  window.requestAnimationFrame       || 
               window.webkitRequestAnimationFrame || 
               window.mozRequestAnimationFrame    || 
               window.oRequestAnimationFrame      || 
               window.msRequestAnimationFrame     || 
              
               function(callback)
               {
                   window.setTimeout(callback);
    			  
               };
    		   
    })();
    
    
    // remove frame margin and scrollbars when maxing out size of canvas
    document.body.style.margin = "0px";
    document.body.style.overflow = "hidden";
    
    
    // get dimensions of window and resize the canvas to fit
    var width = window.innerWidth,
        height = window.innerHeight,
        canvas = document.getElementById('c');
        
        x = canvas.width/2, y = canvas.height/4;
    canvas.width = 1280;
    canvas.height = 720;
    
    // get 2d graphics context and set global alpha
    var G=canvas.getContext("2d");
    G.globalAlpha=0.25;
    
    // setup aliases
    var Rnd = Math.random,
        Sin = Math.sin,
        Floor = Math.floor;
    
    // constants and storage for objects that represent star positions
    var warpZ = 12,
        units = 700,
        stars = [],
        cycle = 0,
        Z = 0.25 + (1/25 * 2),
        t = 0,
        alpha = 0;
    
        
    function addCanvasEventListener(name, fn)
    {
       canvas.addEventListener(name, fn, false);
    }
    addCanvasEventListener(function(e) {
       x = e.clientX;
       y = e.clientY;
    });
    
    function fadeout() {
      
              alpha += warpZ;
            if (alpha >= 1)warpZ = -warpZ;
    }
    
    // function to reset a star object
    function resetstar(a)
    {
       a.x = (Rnd()  * width - (width * 0.5)) * warpZ;
       a.y = (Rnd()  * height - (height * 0.5)) * warpZ;
       a.z = warpZ;
       a.px = 0; 
       a.py = 0;
    
    }
    /*
    function line (e) {
       var delta = 0;
       if (e.detail)
       {
          delta = -e.detail / 0;
       }
       else
       {
          delta = e.lineDelta / 120;
       }
       
       var doff = (delta/25);
       if (delta > 0 && Z+doff <= 0.5 || delta < 0 && Z+doff >= 0.01)
       {
          Z += (delta/25);
       }
    }         
    */
    
    // initial star setup
    for (var i=0, n; i<units; i++)
    {
    
       n = {};
       resetstar(n);
       stars.push(n);
       
    }
    
    // star rendering anim function
    var rf = function(elapsedTime) 
    {
    
    
       G.fillRect(0, 0, width, height);
    
       var cx = (x - width / 2) + (width / 2),
           cy = (y - height / 4) + (height / 4);
       
       // update all stars
       var sat = Floor(Z * 700);       // Z range 0.01 -> 0.5
       if (sat > 150) sat = 150;
       for (var i=0; i<units; i++)
       {
         
          var n = stars[i], // the star
              xx = n.x / n.z,          // star position
              yy = n.y / n.z,
             e = (1.0 / n.z + 1) * 2;   // size i.e. z
    
          if (n.px !== 0)
          {
             // hsl colour from a sine wave
    		 
             G.strokeStyle = "hsl(" + ((cycle * i) % 360) + "," + sat + "%,70%)";
             G.lineWidth = e;
             G.beginPath();
             G.moveTo(xx + cx, yy + cy);
             G.lineTo(n.px + cx, n.py + cy);
             G.stroke();
             
          }
      
          
          
          // update star position values with new settings
          n.px = xx ;
          n.py = yy ;
          n.z -= Z;
          
          // reset when star is out of the view field
          if (n.z < Z || n.px > width || n.py > height)
          {
            resetstar(n);
          } 
          
    		}
    			// colour cycle sinewave rotation
    			cycle += 0.01;
    		
    		 setTimeout(fadeout, 8000);  
    			
    			if (elapsedTime >= 10000)
    			return;
    
    			
    			requestAnimFrame(rf);
    			
    		};
    	
    		requestAnimFrame(rf);
    
    </script>
    
    
    	</body>
    </html>
    and for quick reference here is my site with the animation... Warp Starfield
    Last edited by vinyl-junkie; Oct 1st, 2018 at 07:26 AM. Reason: added code tags

  2. #2
    New Coder
    Join Date
    Jul 2018
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts
    PS Am really good at website design and Php (and was great at AS) and am trying to teach myself new programming languages. But there comes a time when I need to reach out for help.

  3. #3
    Regular Coder
    Join Date
    Apr 2011
    Posts
    190
    Thanks
    0
    Thanked 59 Times in 56 Posts
    The variable Z seems to determine the velocity. For some reason, when velocity is zero (below 0.01) the stars will fade out.
    When you change the bottom of your script to this, you will have a speedup and slowdown to almost zer0 effect;
    Code:
    			// colour cycle sinewave rotation
    			cycle += 0.01;
    
    /*		
    		 setTimeout(fadeout, 8000);  
    			
    			if (elapsedTime >= 10000)
    			return;
    */
    
    if(Z > maxSpeed) {
      acc = deacc;
    }
    if(Z < endSpeed && acc == deacc) {
      acc = 1;
      Z = endSpeed;
    }
    Z *= acc;
    
    			requestAnimFrame(rf);
    			
    		};
    	
    
    startSpeed = 0.01; // min is 0.01
    maxSpeed = 6.5; // max is 6
    endSpeed = 0.01; // min is 0.01
    acc = 1.01; // should be > 1
    deacc = .99 // should be < 1
    
    Z = startSpeed;
    requestAnimFrame(rf);

  4. Users who have thanked Goos for this post:

    whizzbang (Oct 2nd, 2018)

  5. #4
    New Coder
    Join Date
    Jul 2018
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Oh that is absolutely brilliant! Thank you so very much!


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •