Advertisement
Guest User

plax translate2d

a guest
Jun 10th, 2014
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Plax version 1.4.1 */
  2.  
  3. /*
  4.   Copyright (c) 2011 Cameron McEfee
  5.  
  6.   Permission is hereby granted, free of charge, to any person obtaining
  7.   a copy of this software and associated documentation files (the
  8.   "Software"), to deal in the Software without restriction, including
  9.   without limitation the rights to use, copy, modify, merge, publish,
  10.   distribute, sublicense, and/or sell copies of the Software, and to
  11.   permit persons to whom the Software is furnished to do so, subject to
  12.   the following conditions:
  13.  
  14.   The above copyright notice and this permission notice shall be
  15.   included in all copies or substantial portions of the Software.
  16.  
  17.   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18.   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19.   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20.   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  21.   LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  22.   OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  23.   WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. */
  25.  
  26. (function ($) {
  27.  
  28.   var maxfps             = 25,
  29.       delay              = 1 / maxfps * 1000,
  30.       lastRender         = new Date().getTime(),
  31.       layers             = [],
  32.       plaxActivityTarget = $(window),
  33.       motionDegrees      = 30,
  34.       motionMax          = 1,
  35.       motionMin          = -1,
  36.       motionStartX       = null,
  37.       motionStartY       = null,
  38.       ignoreMoveable     = false,
  39.       options            = null;
  40.  
  41.   var defaults = {
  42.     useTransform : true
  43.   };
  44.  
  45.   // Public Methods
  46.   $.fn.plaxify = function (params){
  47.     options = $.extend({}, defaults, params);
  48.     options.useTransform = (options.useTransform);
  49.  
  50.     return this.each(function () {
  51.  
  52.       var layerExistsAt = -1;
  53.       var layer         = {
  54.         "xRange": $(this).data('xrange') || 0,
  55.         "yRange": $(this).data('yrange') || 0,
  56.         "invert": $(this).data('invert') || false,
  57.         "background": $(this).data('background') || false
  58.       };
  59.  
  60.       for (var i=0;i<layers.length;i++){
  61.         if (this === layers[i].obj.get(0)){
  62.           layerExistsAt = i;
  63.         }
  64.       }
  65.  
  66.       for (var param in params) {
  67.         if (layer[param] == 0) {
  68.           layer[param] = params[param];
  69.         }
  70.       }
  71.  
  72.       layer.inversionFactor = (layer.invert ? -1 : 1); // inversion factor for calculations
  73.  
  74.       // Add an object to the list of things to parallax
  75.       layer.obj    = $(this);
  76.       if(layer.background) {
  77.         // animate using the element's background
  78.         pos = (layer.obj.css('background-position') || "0px 0px").split(/ /);
  79.         if(pos.length != 2) {
  80.           return;
  81.         }
  82.         x = pos[0].match(/^((-?\d+)\s*px|0+\s*%|left)$/);
  83.         y = pos[1].match(/^((-?\d+)\s*px|0+\s*%|top)$/);
  84.         if(!x || !y) {
  85.           // no can-doesville, babydoll, we need pixels or top/left as initial values (it mightbe possible to construct a temporary image from the background-image property and get the dimensions and run some numbers, but that'll almost definitely be slow)
  86.           return;
  87.         }
  88.         layer.originX = layer.startX = x[2] || 0;
  89.         layer.originY = layer.startY = y[2] || 0;
  90.         layer.transformOriginX = layer.transformStartX = 0;
  91.         layer.transformOriginY = layer.transformStartY = 0;
  92.  
  93.       } else {
  94.  
  95.         // Figure out where the element is positioned, then reposition it from the top/left, same for transform if using translate
  96.         var position           = layer.obj.position(),
  97.             transformTranslate = getTranslation(layer.obj);
  98.  
  99.         layer.obj.css({
  100.           'transform' : transformTranslate.join() + 'px',
  101.           'top'   : position.top,
  102.           'left'  : position.left,
  103.           'right' :'',
  104.           'bottom':''
  105.         });
  106.         layer.originX = layer.startX = position.left;
  107.         layer.originY = layer.startY = position.top;
  108.         layer.transformOriginX = layer.transformStartX = transformTranslate[0];
  109.         layer.transformOriginY = layer.transformStartY = transformTranslate[1];
  110.       }
  111.  
  112.       layer.startX -= layer.inversionFactor * Math.floor(layer.xRange/2);
  113.       layer.startY -= layer.inversionFactor * Math.floor(layer.yRange/2);
  114.  
  115.       layer.transformStartX -= layer.inversionFactor * Math.floor(layer.xRange/2);
  116.       layer.transformStartY -= layer.inversionFactor * Math.floor(layer.yRange/2);
  117.  
  118.       if(layerExistsAt >= 0){
  119.         layers.splice(layerExistsAt,1,layer);
  120.       } else {
  121.         layers.push(layer);
  122.       }
  123.  
  124.     });
  125.   };
  126.  
  127.   // Get the translate position of the element
  128.   //
  129.   // return 2 element array for translate
  130.   function getTranslation(obj) {
  131.     var translate = [0,0],
  132.         matrix    = obj.css("-webkit-transform") ||
  133.                     obj.css("-moz-transform")    ||
  134.                     obj.css("-ms-transform")     ||
  135.                     obj.css("-o-transform")      ||
  136.                     obj.css("transform");
  137.  
  138.     if(matrix !== 'none') {
  139.       var values = matrix.split('(')[1].split(')')[0].split(',');
  140.       var x = (parseFloat(values[values.length - 2])),
  141.           y = (parseFloat(values[values.length - 1]));
  142.        
  143.       translate = [x,y];
  144.     }
  145.     return translate;
  146.   }
  147.  
  148.   // Check if element is in viewport area
  149.   //
  150.   // Returns boolean
  151.   function inViewport(element) {
  152.     if (element.offsetWidth === 0 || element.offsetHeight === 0) return false;
  153.  
  154.     var height = document.documentElement.clientHeight,
  155.       rects  = element.getClientRects();
  156.  
  157.     for (var i = 0, l = rects.length; i < l; i++) {
  158.  
  159.     var r           = rects[i],
  160.         in_viewport = r.top > 0 ? r.top <= height : (r.bottom > 0 && r.bottom <= height);
  161.  
  162.     if (in_viewport) return true;
  163.     }
  164.     return false;
  165.   }
  166.  
  167.   // Determine if the device has an accelerometer
  168.   //
  169.   // returns true if the browser has window.DeviceMotionEvent (mobile)
  170.   function moveable(){
  171.     return (ignoreMoveable===true) ? false : window.DeviceOrientationEvent !== undefined;
  172.   }
  173.  
  174.   // The values pulled from the gyroscope of a motion device.
  175.   //
  176.   // Returns an object literal with x and y as options.
  177.   function valuesFromMotion(e) {
  178.     x = e.gamma;
  179.     y = e.beta;
  180.  
  181.     // Swap x and y in Landscape orientation
  182.     if (Math.abs(window.orientation) === 90) {
  183.       var a = x;
  184.       x = y;
  185.       y = a;
  186.     }
  187.  
  188.     // Invert x and y in upsidedown orientations
  189.     if (window.orientation < 0) {
  190.       x = -x;
  191.       y = -y;
  192.     }
  193.  
  194.     motionStartX = (motionStartX === null) ? x : motionStartX;
  195.     motionStartY = (motionStartY === null) ? y : motionStartY;
  196.  
  197.     return {
  198.       x: x - motionStartX,
  199.       y: y - motionStartY
  200.     };
  201.   }
  202.  
  203.   // Move the elements in the `layers` array within their ranges,
  204.   // based on mouse or motion input
  205.   //
  206.   // Parameters
  207.   //
  208.   //  e - mousemove or devicemotion event
  209.   //
  210.   // returns nothing
  211.   function plaxifier(e) {
  212.     if (new Date().getTime() < lastRender + delay) return;
  213.       lastRender = new Date().getTime();
  214.  
  215.     var leftOffset = (plaxActivityTarget.offset() != null) ? plaxActivityTarget.offset().left : 0,
  216.         topOffset  = (plaxActivityTarget.offset() != null) ? plaxActivityTarget.offset().top : 0,
  217.         x          = e.pageX-leftOffset,
  218.         y          = e.pageY-topOffset;
  219.  
  220.     if (!inViewport(layers[0].obj[0].parentNode)) return;
  221.  
  222.     if(moveable()){
  223.       if(e.gamma === undefined){
  224.         ignoreMoveable = true;
  225.         return;
  226.       }
  227.       values = valuesFromMotion(e);
  228.  
  229.       // Admittedly fuzzy measurements
  230.       x = values.x / motionDegrees;
  231.       y = values.y / motionDegrees;
  232.       // Ensure not outside of expected range, -1 to 1
  233.       x = x < motionMin ? motionMin : (x > motionMax ? motionMax : x);
  234.       y = y < motionMin ? motionMin : (y > motionMax ? motionMax : y);
  235.       // Normalize from -1 to 1 => 0 to 1
  236.       x = (x + 1) / 2;
  237.       y = (y + 1) / 2;
  238.     }
  239.  
  240.     var hRatio = x/((moveable() === true) ? motionMax : plaxActivityTarget.width()),
  241.         vRatio = y/((moveable() === true) ? motionMax : plaxActivityTarget.height()),
  242.         layer, i;
  243.  
  244.     for (i = layers.length; i--;) {
  245.       layer = layers[i];
  246.       if(options.useTransform && !layer.background){
  247.         newX = layer.transformStartX + layer.inversionFactor*(layer.xRange*hRatio);
  248.         newY = layer.transformStartY + layer.inversionFactor*(layer.yRange*vRatio);
  249.         layer.obj
  250.             .css({'transform':'translate('+newX+'px,'+newY+'px)'});
  251.       }else{
  252.         newX = layer.startX + layer.inversionFactor*(layer.xRange*hRatio);
  253.         newY = layer.startY + layer.inversionFactor*(layer.yRange*vRatio);
  254.         if(layer.background) {
  255.           layer.obj
  256.             .css('background-position', newX+'px '+newY+'px');
  257.         } else {
  258.           layer.obj
  259.             .css('left', newX)
  260.             .css('top', newY);
  261.         }
  262.       }
  263.     }
  264.   }
  265.  
  266.   $.plax = {
  267.     // Begin parallaxing
  268.     //
  269.     // Parameters
  270.     //
  271.     //  opts - options for plax
  272.     //    activityTarget - optional; plax will only work within the bounds of this element, if supplied.
  273.     //
  274.     //  Examples
  275.     //
  276.     //    $.plax.enable({ "activityTarget": $('#myPlaxDiv')})
  277.     //    # plax only happens when the mouse is over #myPlaxDiv
  278.     //
  279.     // returns nothing
  280.     enable: function(opts){
  281.       if (opts) {
  282.         if (opts.activityTarget) plaxActivityTarget = opts.activityTarget || $(window);
  283.         if (typeof opts.gyroRange === 'number' && opts.gyroRange > 0) motionDegrees = opts.gyroRange;
  284.       }
  285.  
  286.       plaxActivityTarget.bind('mousemove.plax', function (e) {
  287.         plaxifier(e);
  288.       });
  289.  
  290.       if(moveable()){
  291.         window.ondeviceorientation = function(e){plaxifier(e);};
  292.       }
  293.  
  294.     },
  295.  
  296.     // Stop parallaxing
  297.     //
  298.     //  Examples
  299.     //
  300.     //    $.plax.disable()
  301.     //    # plax no longer runs
  302.     //
  303.     //    $.plax.disable({ "clearLayers": true })
  304.     //    # plax no longer runs and all layers are forgotten
  305.     //
  306.     // returns nothing
  307.     disable: function(opts){
  308.       $(document).unbind('mousemove.plax');
  309.       window.ondeviceorientation = undefined;
  310.       if (opts && typeof opts.restorePositions === 'boolean' && opts.restorePositions) {
  311.         for(var i = layers.length; i--;) {
  312.           layer = layers[i];
  313.           if(options.useTransform && !layer.background){
  314.             layer.obj
  315.                 .css('transform', 'translate('+layer.transformOriginX+'px,'+layer.transformOriginY+'px)')
  316.                 .css('top', layer.originY);
  317.           }else{
  318.             if(layers[i].background) {
  319.               layer.obj.css('background-position', layer.originX+'px '+layer.originY+'px');
  320.             } else {
  321.               layer.obj
  322.                 .css('left', layer.originX)
  323.                 .css('top', layer.originY);
  324.             }
  325.           }
  326.         }
  327.       }
  328.       if (opts && typeof opts.clearLayers === 'boolean' && opts.clearLayers) layers = [];
  329.     }
  330.   };
  331.  
  332.   if (typeof ender !== 'undefined') {
  333.     $.ender($.fn, true);
  334.   }
  335.  
  336. })(function () {
  337.   return typeof jQuery !== 'undefined' ? jQuery : ender;
  338. }());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement