plax.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /* Plax version 1.3.1 */
  2. /*
  3. Copyright (c) 2011 Cameron McEfee
  4. Permission is hereby granted, free of charge, to any person obtaining
  5. a copy of this software and associated documentation files (the
  6. "Software"), to deal in the Software without restriction, including
  7. without limitation the rights to use, copy, modify, merge, publish,
  8. distribute, sublicense, and/or sell copies of the Software, and to
  9. permit persons to whom the Software is furnished to do so, subject to
  10. the following conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  17. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  18. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  19. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. */
  21. (function ($) {
  22. var maxfps = 25,
  23. delay = 1 / maxfps * 1000,
  24. lastRender = new Date().getTime(),
  25. layers = [],
  26. plaxActivityTarget = $(window),
  27. motionEnabled = false,
  28. motionMax = 1,
  29. motionAllowance = .05,
  30. movementCycles = 0,
  31. motionLowPassFilter= 0.05,
  32. motionLastX = 1,
  33. motionLastY = 1,
  34. motionData = {
  35. "xArray" : [0,0,0,0,0],
  36. "yArray" : [0,0,0,0,0],
  37. "xMotion" : 0,
  38. "yMotion" : 0
  39. }
  40. // Public Methods
  41. $.fn.plaxify = function (params){
  42. return this.each(function () {
  43. var layerExistsAt = -1
  44. var layer = {
  45. "xRange": $(this).data('xrange') || 0,
  46. "yRange": $(this).data('yrange') || 0,
  47. "invert": $(this).data('invert') || false,
  48. "background": $(this).data('background') || false
  49. }
  50. for (var i=0;i<layers.length;i++){
  51. if (this === layers[i].obj.get(0)){
  52. layerExistsAt = i
  53. }
  54. }
  55. for (var param in params) {
  56. if (layer[param] == 0) {
  57. layer[param] = params[param]
  58. }
  59. }
  60. layer.inversionFactor = (layer.invert ? -1 : 1) // inversion factor for calculations
  61. // Add an object to the list of things to parallax
  62. layer.obj = $(this)
  63. if(layer.background) {
  64. // animate using the element's background
  65. pos = (layer.obj.css('background-position') || "0px 0px").split(/ /)
  66. if(pos.length != 2) {
  67. return
  68. }
  69. x = pos[0].match(/^((-?\d+)\s*px|0+\s*%|left)$/)
  70. y = pos[1].match(/^((-?\d+)\s*px|0+\s*%|top)$/)
  71. if(!x || !y) {
  72. // 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)
  73. return
  74. }
  75. layer.startX = x[2] || 0
  76. layer.startY = y[2] || 0
  77. } else {
  78. // Figure out where the element is positioned, then reposition it from the top/left
  79. var position = layer.obj.position()
  80. layer.obj.css({
  81. 'top' : position.top,
  82. 'left' : position.left,
  83. 'right' :'',
  84. 'bottom':''
  85. })
  86. layer.startX = this.offsetLeft
  87. layer.startY = this.offsetTop
  88. }
  89. layer.startX -= layer.inversionFactor * Math.floor(layer.xRange/2)
  90. layer.startY -= layer.inversionFactor * Math.floor(layer.yRange/2)
  91. if(layerExistsAt >= 0){
  92. layers.splice(layerExistsAt,1,layer)
  93. } else {
  94. layers.push(layer)
  95. }
  96. })
  97. }
  98. // Get minimum value of an array
  99. //
  100. // arr - array to be tested
  101. //
  102. // returns the smallest value in the array
  103. function getMin(arr){
  104. return Math.min.apply({}, arr)
  105. }
  106. // Get maximum value of an array
  107. //
  108. // arr - array to be tested
  109. //
  110. // returns the largest value in the array
  111. function getMax(arr){
  112. return Math.max.apply({}, arr)
  113. }
  114. // Determine if the device has an accelerometer
  115. //
  116. // returns true if the browser has window.DeviceMotionEvent (mobile)
  117. function moveable(){
  118. return window.DeviceMotionEvent != undefined
  119. }
  120. // Determine if the device is actually moving. If it is, enable motion based parallaxing.
  121. // Otherwise, use the mouse to parallax
  122. //
  123. // Parameters
  124. //
  125. // e - devicemotion event
  126. //
  127. // returns nothing
  128. function detectMotion(e){
  129. if (new Date().getTime() < lastRender + delay) return
  130. if(moveable()){
  131. var accel= e.accelerationIncludingGravity,
  132. x = accel.x,
  133. y = accel.y
  134. x = (x * motionLowPassFilter) + (motionLastX * (1.0 - motionLowPassFilter));
  135. y = (y * motionLowPassFilter) + (motionLastY * (1.0 - motionLowPassFilter));
  136. motionLastX = x;
  137. motionLastY = y;
  138. if(motionData.xArray.length >= 5){
  139. motionData.xArray.shift()
  140. }
  141. if(motionData.yArray.length >= 5){
  142. motionData.yArray.shift()
  143. }
  144. motionData.xArray.push(x)
  145. motionData.yArray.push(y)
  146. motionData.xMotion = Math.round((getMax(motionData.xArray) - getMin(motionData.xArray))*1000)/1000
  147. motionData.yMotion = Math.round((getMax(motionData.yArray) - getMin(motionData.yArray))*1000)/1000
  148. if((motionData.xMotion > 1.5 || motionData.yMotion > 1.5)) {
  149. if(motionMax!=10){
  150. motionMax = 10
  151. }
  152. }
  153. // test for sustained motion
  154. if(motionData.xMotion > motionAllowance || motionData.yMotion > motionAllowance){
  155. movementCycles++;
  156. } else {
  157. movementCycles = 0;
  158. }
  159. if(movementCycles >= 5){
  160. motionEnabled = true
  161. $(document).unbind('mousemove.plax')
  162. //window.ondevicemotion = function(e){plaxifier(e)}
  163. $(window).bind('devicemotion', plaxifier(e))
  164. } else {
  165. motionEnabled = false
  166. $(window).unbind('devicemotion')
  167. $(document).bind('mousemove.plax', function (e) {
  168. plaxifier(e)
  169. })
  170. }
  171. }
  172. }
  173. // Move the elements in the `layers` array within their ranges,
  174. // based on mouse or motion input
  175. //
  176. // Parameters
  177. //
  178. // e - mousemove or devicemotion event
  179. //
  180. // returns nothing
  181. function plaxifier(e) {
  182. if (new Date().getTime() < lastRender + delay) return
  183. lastRender = new Date().getTime()
  184. var leftOffset = (plaxActivityTarget.offset() != null) ? plaxActivityTarget.offset().left : 0,
  185. topOffset = (plaxActivityTarget.offset() != null) ? plaxActivityTarget.offset().top : 0,
  186. x = e.pageX-leftOffset,
  187. y = e.pageY-topOffset
  188. if (
  189. x < 0 || x > plaxActivityTarget.width() ||
  190. y < 0 || y > plaxActivityTarget.height()
  191. ) return
  192. if(motionEnabled == true){
  193. // portrait(%2==0) or landscape
  194. var i = window.orientation ? (window.orientation + 180) % 360 / 90 : 2,
  195. accel= e.accelerationIncludingGravity,
  196. tmp_x = i%2==0 ? -accel.x : accel.y,
  197. tmp_y = i%2==0 ? accel.y : accel.x
  198. // facing up(>=2) or down
  199. x = i>=2 ? tmp_x : -tmp_x
  200. y = i>=2 ? tmp_y : -tmp_y
  201. // change value from a range of -x to x => 0 to 1
  202. x = (x+motionMax)/2
  203. y = (y+motionMax)/2
  204. // keep values within range
  205. if(x < 0 ){
  206. x = 0
  207. } else if( x > motionMax ) {
  208. x = motionMax
  209. }
  210. if(y < 0 ){
  211. y = 0
  212. } else if( y > motionMax ) {
  213. y = motionMax
  214. }
  215. }
  216. var hRatio = x/((motionEnabled == true) ? motionMax : plaxActivityTarget.width()),
  217. vRatio = y/((motionEnabled == true) ? motionMax : plaxActivityTarget.height()),
  218. layer, i
  219. for (i = layers.length; i--;) {
  220. layer = layers[i]
  221. newX = layer.startX + layer.inversionFactor*(layer.xRange*hRatio)
  222. newY = layer.startY + layer.inversionFactor*(layer.yRange*vRatio)
  223. if(layer.background) {
  224. layer.obj.css('background-position', newX+'px '+newY+'px')
  225. } else {
  226. layer.obj
  227. .css('left', newX)
  228. .css('top', newY)
  229. }
  230. }
  231. }
  232. $.plax = {
  233. // Begin parallaxing
  234. //
  235. // Parameters
  236. //
  237. // opts - options for plax
  238. // activityTarget - optional; plax will only work within the bounds of this element, if supplied.
  239. //
  240. // Examples
  241. //
  242. // $.plax.enable({ "activityTarget": $('#myPlaxDiv')})
  243. // # plax only happens when the mouse is over #myPlaxDiv
  244. //
  245. // returns nothing
  246. enable: function(opts){
  247. $(document).bind('mousemove.plax', function (e) {
  248. if(opts){
  249. plaxActivityTarget = opts.activityTarget || $(window)
  250. }
  251. plaxifier(e)
  252. })
  253. if(moveable()){
  254. window.ondevicemotion = function(e){detectMotion(e)}
  255. }
  256. },
  257. // Stop parallaxing
  258. //
  259. // Examples
  260. //
  261. // $.plax.disable()
  262. // # plax no longer runs
  263. //
  264. // returns nothing
  265. disable: function(){
  266. $(document).unbind('mousemove.plax')
  267. window.ondevicemotion = undefined
  268. }
  269. }
  270. if (typeof ender !== 'undefined') {
  271. $.ender($.fn, true)
  272. }
  273. })(function () {
  274. return typeof jQuery !== 'undefined' ? jQuery : ender
  275. }())