Advertisement
Guest User

RequestAnimationFrame code

a guest
Mar 6th, 2013
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*  * Project  :   TSO Road Heros Canvas Animation
  2.     * Author   :   Jay Smith of MMK Media
  3.     * Version  :   1.0
  4. */
  5. if ( !window.requestAnimationFrame ) {
  6.   window.requestAnimationFrame = ( function() {
  7.     return  window.webkitRequestAnimationFrame ||
  8.                 window.mozRequestAnimationFrame ||
  9.                 window.oRequestAnimationFrame ||
  10.                 window.msRequestAnimationFrame ||
  11.                 function(callback) {
  12.                    window.setTimeout( callback, 1000 / 105, new Date()); };
  13.     } )();
  14. }
  15.  
  16. //set timeout function to control time the script runs if needed - mostly for testing.
  17. //Set up some vars -------------------------------------------------------------
  18. stageHeight =  window.innerHeight;
  19. stageWidth = window.innerWidth;
  20. //window.requestAnimationFrame = (function(callback){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(callback, 1000 / 60); };})();
  21. //Load all of the Images from the Sources Array - Preload Trick ----------------
  22. function loadImages(sources, callback) {
  23.       var images = {};
  24.       var loadedImages = 0;
  25.       var numImages = 0;
  26.       // get num of sources
  27.       for(var src in sources) {
  28.         numImages++;
  29.       }
  30.       for(var src in sources) {
  31.         images[src] = new Image();
  32.         images[src].onload = function() {
  33.           if(++loadedImages >= numImages) {
  34.             callback(images);
  35.           }
  36.         };
  37.         images[src].src = sources[src];
  38.       }
  39. }
  40.  
  41. //Set up the Stage. ------------------------------------------------------------
  42. function draw(images)  {        
  43.     var stage = new Kinetic.Stage({
  44.           container: 'container',
  45.           width: stageWidth,
  46.           height: stageHeight
  47.     });
  48.  
  49.     //Set up the Layers. -----------------------------------------------------------
  50.  
  51.     var charactersLayerBG = new Kinetic.Layer();
  52.     var introLayer = new Kinetic.Layer();
  53.  
  54.     var introGroup = new Kinetic.Group();
  55.  
  56. //----- INTRO CHARACTERS-----------------------------------------------
  57. //Amber green body, behind the jaws.
  58. var AmberGreenBody = new Kinetic.Image({
  59.     x: -340 ,
  60.     y: stageHeight - 360,
  61.     width: 335,
  62.     height: 375,
  63.    fillPatternImage: images.amberGreenBody
  64. });
  65.  
  66.  
  67. //have to seperate layers as her arm has to be on a different Z-Index to her body! :(
  68. charactersLayerBG.add(AmberGreenBody);
  69.  
  70.  
  71. //Ambder green speech bubble.
  72. var AmberGreenSpeechBubble = new Kinetic.Shape({
  73.     x: 380,
  74.     y:stageHeight - 220,
  75.     fill: 'black',
  76.     opacity: 0.85,
  77.     stroke: 'black',
  78.     strokeWidth: 4,
  79.     offset: {
  80.         x: 0,
  81.         y: 240
  82.     },
  83.     scale: {
  84.         x: 1,
  85.         y: 1
  86.     },
  87.     shadow: {
  88.         color: 'black',
  89.         blur: 0,
  90.         offset: [3, 3],
  91.         opacity: 0.4
  92.    },
  93.     drawFunc: function (canvas) {
  94.         var context = canvas.getContext();
  95.         context.beginPath();
  96.         context.moveTo(0, 0);
  97.         context.lineTo(300, 20);
  98.         context.lineTo(290, 200);
  99.         context.lineTo(50, 200);
  100.         context.lineTo(-30, 250);
  101.         context.lineTo(15, 200);
  102.         context.lineTo(-10, 195)
  103.         context.closePath();
  104.         canvas.fillStroke(this);
  105.     }
  106. });
  107.  
  108. var AmberGreenSpeechBubbleText = new Kinetic.Text({
  109.         x: 400,
  110.         y: stageHeight -200,
  111.         text: 'Gadzooks! look at all \n \n that traffic! there must \n \n have been an accident!!',
  112.         width:359,
  113.         height:150,
  114.         fontSize: 26,
  115.         offset: [0, 240],
  116.         fontFamily: 'Bangers',
  117.         padding: 8,  
  118.         scale: {x:1, y:1},
  119.         fill: "#ccc"
  120. });
  121.  
  122. charactersLayerBG.add(AmberGreenSpeechBubble);
  123. charactersLayerBG.add(AmberGreenSpeechBubbleText);
  124.  
  125.  
  126. //The Cone body, behind the jaws.
  127. var TheConeBody = new Kinetic.Image({
  128.     x: -340 ,
  129.     y: stageHeight - 400,
  130.     width: 299,
  131.     height: 337,
  132.     fillPatternImage:images.TheConeBody
  133. });
  134.  
  135. charactersLayerBG.add(TheConeBody);
  136.  
  137.  
  138. // Background for Intro Later - Road ----
  139. var roadBG = new Kinetic.Image({
  140.     x:0,
  141.     y: stageHeight / 2 - 580,
  142.     width:stageWidth,
  143.     height:852,
  144.    fillPatternImage: images.introRoadBG
  145.          
  146. });
  147.  
  148. var bottomOfRoad = new Kinetic.Image({
  149.     x:0,
  150.     y:stageHeight / 2 + 271,
  151.     width:stageWidth,
  152.     height:101,
  153.     fillPatternImage: images.bottomOfRoad
  154. });
  155.  
  156. var water = new Kinetic.Image({
  157.     x:0,
  158.     y: stageHeight / 2 + 310,
  159.     width: stageWidth,
  160.     height: 640,
  161.     fillPatternImage: images.water
  162. });
  163.  
  164.        
  165.  
  166. //Add intro objects to the introLayer
  167. introGroup.add(water);
  168. introGroup.add(roadBG);
  169. introGroup.add(bottomOfRoad);
  170. //buildCarsLaneOne(stageWidth, stageHeight);
  171.            
  172.            
  173.     introLayer.add(introGroup);
  174.  
  175.     stage.add(introLayer);
  176.     stage.add(charactersLayerBG);
  177.  
  178.  
  179.     var IntroAnimation = new Animation('IntroAnimation', "introTimeline", true, 0 [
  180.                                                               //ObjectKeyFrame(time,posX,posY,rotation,scale,opacity,easing){
  181.                                 introGroupTimeline = new ObjectTimeline(introGroup,[
  182.                                                             new ObjectKeyFrame(0,       0,     0, 0, 1, 1, "ease-out"),
  183.                                                             new ObjectKeyFrame(15000,   -stageWidth / 2,   0, 0, 1, 1, "ease-out"),
  184.                                                             new ObjectKeyFrame(15000,   -stageWidth / 2,   0, 0, 1, 1, "ease-out")
  185.                                                            
  186.                                                         ]),
  187.                                                              
  188.                                 AmberGreenBodyTimeline = new ObjectTimeline(AmberGreenBody,[
  189.                                                             new ObjectKeyFrame(0,     -550,  stageHeight - 360, 0, 1, 1, "ease-out"),
  190.                                                             new ObjectKeyFrame(3000,   90,   stageHeight - 360, 0, 1, 1, "ease-out"),
  191.                                                             new ObjectKeyFrame(3000,   90,   stageHeight - 360, 0, 1, 1, "ease-out")
  192.                                                            
  193.                                                         ]),
  194.                                                        
  195.                                 AmberGreenSpeechBubbleTimeline = new ObjectTimeline(AmberGreenSpeechBubble, [
  196.                                                                         new ObjectKeyFrame(0,     380,     stageHeight - 220, 0, 0, 1, "ease-out"),
  197.                                                                         new ObjectKeyFrame(2000,  380,     stageHeight - 220, 0, 0, 1, "ease-out"),
  198.                                                                         new ObjectKeyFrame(3000,  380,     stageHeight - 220, 0, 1, 1, "ease-out"),
  199.                                                                         new ObjectKeyFrame(8000,  380,     stageHeight - 220, 0, 1, 1, "ease-out"),
  200.                                                                         new ObjectKeyFrame(9000,  380,     stageHeight - 220, 0, 0, 0, "ease-out"),
  201.                                                                         new ObjectKeyFrame(9000,  380,     stageHeight - 220, 0, 0, 0, "ease-out")
  202.                                                                        
  203.                                 ]),
  204.                                                        
  205.                                 AmberGreenSpeechBubbleTextTimeline = new ObjectTimeline(AmberGreenSpeechBubbleText, [
  206.                                                                         new ObjectKeyFrame(0,     400,     stageHeight - 200, 0, 0, 1, "ease-out"),
  207.                                                                         new ObjectKeyFrame(2500,  400,     stageHeight - 200, 0, 0, 1, "ease-out"),
  208.                                                                         new ObjectKeyFrame(3000,  400,     stageHeight - 200, 0, 1, 1, "ease-out"),
  209.                                                                         new ObjectKeyFrame(8000,  400,     stageHeight - 200, 0, 1, 1, "ease-out"),
  210.                                                                         new ObjectKeyFrame(9000,  400,     stageHeight - 200, 0, 0, 0, "ease-out"),
  211.                                                                         new ObjectKeyFrame(9000,  400,     stageHeight - 200, 0, 0, 0, "ease-out")
  212.                                                                        
  213.                                 ]),
  214.                                
  215.                                 theConeBodyTimeline = new ObjectTimeline(TheConeBody, [
  216.                                                                 new ObjectKeyFrame(0,     -340,     stageHeight - 400, 0, 1, 1, "ease-out"),
  217.                                                                 new ObjectKeyFrame(6000,     -340,     stageHeight - 400, 0, 1, 1, "ease-out"),
  218.                                                                 new ObjectKeyFrame(7500,     390,     stageHeight - 400, 0, 1, 1, "ease-out"),
  219.                                                                 new ObjectKeyFrame(8000,     410,     stageHeight - 400, 0, 1, 1, "ease-out")
  220.                                 ])
  221.    ]);
  222.  
  223.   introTimeline = [
  224.                 AmberGreenBodyTimeline,
  225.                 AmberGreenSpeechBubbleTimeline,
  226.                 AmberGreenSpeechBubbleTextTimeline,
  227.                 theConeBodyTimeline
  228.                    
  229.                
  230.    ]
  231.    
  232.  
  233.  
  234.     //Run the animation Function to check if any animatoin objects should be running.
  235.     function Animate(){  
  236.         //Array of all possible animations.
  237.         animations = [
  238.                        IntroAnimation
  239.                      ]
  240.         //For each animation object. If its supposed to be running go and do the runAnimation Function.
  241.           $.each(animations,function(){
  242.               if (this.animating === true){
  243.                   runAnimation(this);
  244.               }
  245.           });  
  246.          
  247.     }
  248.                  
  249.     function runAnimation(animation){
  250.        
  251.         newAnimTime = new Date().getTime();
  252.         animationTime = parseInt(newAnimTime - animation.animationStart);
  253.  
  254.         var t = animationTime; //Animation Time
  255.         var kf = 0; //Current KeyFrame
  256.         var tl = 0; //Current Timeline Item
  257.         var timeFrames = []; //Array to build Keyframes
  258.         var timeline = animation.timeline; //Timeline to use for Current Animation
  259.             //for each of the timeline itesm tun the SetObjects Function
  260.         $.each(this[timeline],function(){
  261.              setObjects(tl);              
  262.              tl++; //Increment tl by One.
  263.         });
  264.            
  265.         //Function to put each keyframe into its own array item.
  266.         function setObjects(timelineNo){
  267.            
  268.             kf = 0; //Reset Keyframe Number
  269.             timeFrames = []; //Reset / empty timeFrames Array.
  270.      
  271.             //put each timeframe into an array item.
  272.              $.each(this[timeline][timelineNo].keyframes, function(){
  273.                 timeFrames[kf] = this;
  274.                 kf++; //increment kf by one.
  275.              });
  276.  
  277.              //once the objects and keyframes have been setup run setNewVars();
  278.             setNewVars(timeFrames,this[timeline][timelineNo].name);
  279.          }
  280.              
  281.            
  282.         //function which goes through each timeFrame
  283.         function setNewVars(timeFrames, object){
  284.            
  285.                 var currentKF = 0; //Setup the currentKF.
  286.                
  287.                 //For each time frame array item work out whic keyframe is the start and end.
  288.                 $.each(timeFrames,function(){
  289.  
  290.                 //if the timeframes time is smaller of = to t then -
  291.                    if((timeFrames[currentKF].time >= t)){
  292.  
  293.                         //if t is not = to 0 then
  294.                         if(t !== 0){
  295.  
  296.                                 startTimeFrame = timeFrames[currentKF - 1]; //The start frame is the keyframe before current one
  297.                                 endTimeFrame = timeFrames[currentKF]; //End time frame is this current Keyframe.
  298.  
  299.                                 //Work out the ratio.
  300.                                 var Ratio = (t - startTimeFrame.time) / (endTimeFrame.time - startTimeFrame.time);
  301.                                 var newX = startTimeFrame.posX + ((endTimeFrame.posX - startTimeFrame.posX) * Ratio); //New X Value;
  302.                                 var newY = startTimeFrame.posY + ((endTimeFrame.posY - startTimeFrame.posY) * Ratio); //New X Value;
  303.                                 var newOpacity = startTimeFrame.opacity + ((endTimeFrame.opacity - startTimeFrame.opacity) * Ratio); //New Opacity Value
  304.                                 var newRotation = startTimeFrame.rotation + ((endTimeFrame.rotation - startTimeFrame.rotation) * Ratio);
  305.                                 var newScale = startTimeFrame.scale + ((endTimeFrame.scale - startTimeFrame.scale) * Ratio);
  306.                                
  307.                                 //Actually update the object on this frame with the new values
  308.                                 object.setX(newX);
  309.                                 object.setY(newY);
  310.                                 object.setOpacity(newOpacity);
  311.                                 object.setRotation(newRotation);
  312.                                 object.setScale(newScale);
  313.                        
  314.                                 stage.draw();
  315.                                
  316.                                  return;
  317.                         }
  318.                    }
  319.  
  320.                    currentKF++;
  321.                 }); //End of each Keyframe
  322.         }  
  323.      
  324.                        
  325.       setTimeout(function(){
  326.            requestAnimationFrame(Animate);
  327.            },1000/16.5);                          
  328.                    
  329. }
  330.        
  331.  //Initial Animate Request
  332.  
  333. IntroAnimation.animationStart = new Date().getTime();
  334. requestAnimationFrame(Animate);
  335.  
  336.  
  337.     function Animation(name, timeline, animating, animationStart){
  338.             this.name = name;
  339.             this.timeline = timeline;
  340.             this.animating = animating;
  341.             this.animationStart = animationStart;
  342.     }    
  343.  
  344.     function ObjectTimeline(name,keyframes){
  345.             this.name = name;
  346.             this.keyframes = keyframes;
  347.             this._classname = "MoveObject";
  348.     }
  349.  
  350.     function ObjectKeyFrame(time,posX,posY,rotation,scale,opacity,easing){
  351.             this.time = time;
  352.             this.posX = posX;
  353.             this.posY = posY;
  354.             this.rotation = ( Math.PI / ( 360 / rotation ) ) *2;
  355.             this.scale = scale;
  356.             this.opacity = opacity;
  357.             this.easing = easing;
  358.     }
  359.  
  360.  
  361.  
  362.  
  363. } //End of the main Draw Function.----------------------------------------------
  364.                    
  365. //Image sources ----------------------------------------------------------------
  366. var sources = {
  367.        
  368.         amberGreenBody: 'canvas/imgs/chars/amber-green-worry-behind.png',
  369.         TheConeBody: 'canvas/imgs/chars/cone-look-behind.png',
  370.         dynamoDanBody: 'canvas/imgs/chars/dan-smile-behind.png',
  371.         introRoadBG: 'canvas/imgs/intro/background/roadBG.png',
  372.         bottomOfRoad: 'canvas/imgs/intro/background/bottomOfRoad.png',
  373.         water: 'canvas/imgs/intro/background/water.png',
  374.         beatlesCarSprite: 'canvas/imgs/intro/cars/beatles-car.png',
  375.         compactCarSprite: 'canvas/imgs/intro/cars/compact-car.png',
  376.         rangeCarSprite: 'canvas/imgs/intro/cars/rangerover-car.png',
  377.         sedanCarSprite: 'canvas/imgs/intro/cars/sedan-car.png'  
  378.       };
  379.  
  380.  
  381.     //Once all the images are loaded draw the Canvas. ------------------------------
  382.     loadImages(sources, function(images) {
  383.      draw(images);
  384.     });
  385.  
  386. //END OF CODE END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement