Advertisement
cmintey

SnowFall

Dec 11th, 2014
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.18 KB | None | 0 0
  1. /** @license
  2. * DHTML Snowstorm! JavaScript-based snow for web pages
  3. * Making it snow on the internets since 2003. You're welcome.
  4. * -----------------------------------------------------------
  5. * Version 1.44.20131215 (Previous rev: 1.44.20131208)
  6. * Copyright (c) 2007, Scott Schiller. All rights reserved.
  7. * Code provided under the BSD License
  8. * http://schillmania.com/projects/snowstorm/license.txt
  9. */
  10. /*jslint nomen: true, plusplus: true, sloppy: true, vars: true, white: true */
  11. /*global window, document, navigator, clearInterval, setInterval */
  12. var snowStorm = (function(window, document) {
  13. // --- common properties ---
  14. this.autoStart = true; // Whether the snow should start automatically or not.
  15. this.excludeMobile = true; // Snow is likely to be bad news for mobile phones' CPUs (and batteries.) Enable at your own risk.
  16. this.flakesMax = 128; // Limit total amount of snow made (falling + sticking)
  17. this.flakesMaxActive = 64; // Limit amount of snow falling at once (less = lower CPU use)
  18. this.animationInterval = 33; // Theoretical "miliseconds per frame" measurement. 20 = fast + smooth, but high CPU use. 50 = more conservative, but slower
  19. this.useGPU = true; // Enable transform-based hardware acceleration, reduce CPU load.
  20. this.className = null; // CSS class name for further customization on snow elements
  21. this.excludeMobile = true; // Snow is likely to be bad news for mobile phones' CPUs (and batteries.) By default, be nice.
  22. this.flakeBottom = null; // Integer for Y axis snow limit, 0 or null for "full-screen" snow effect
  23. this.followMouse = false; // Snow movement can respond to the user's mouse
  24. this.snowColor = '#99ccff'; // Don't eat (or use?) yellow snow.
  25. this.snowCharacter = '•'; // • = bullet, · is square on some systems etc.
  26. this.snowStick = true; // Whether or not snow should "stick" at the bottom. When off, will never collect.
  27. this.targetElement = null; // element which snow will be appended to (null = document.body) - can be an element ID eg. 'myDiv', or a DOM node reference
  28. this.useMeltEffect = true; // When recycling fallen snow (or rarely, when falling), have it "melt" and fade out if browser supports it
  29. this.useTwinkleEffect = false; // Allow snow to randomly "flicker" in and out of view while falling
  30. this.usePositionFixed = false; // true = snow does not shift vertically when scrolling. May increase CPU load, disabled by default - if enabled, used only where supported
  31. this.usePixelPosition = false; // Whether to use pixel values for snow top/left vs. percentages. Auto-enabled if body is position:relative or targetElement is specified.
  32. // --- less-used bits ---
  33. this.freezeOnBlur = true; // Only snow when the window is in focus (foreground.) Saves CPU.
  34. this.flakeLeftOffset = 0; // Left margin/gutter space on edge of container (eg. browser window.) Bump up these values if seeing horizontal scrollbars.
  35. this.flakeRightOffset = 0; // Right margin/gutter space on edge of container
  36. this.flakeWidth = 8; // Max pixel width reserved for snow element
  37. this.flakeHeight = 8; // Max pixel height reserved for snow element
  38. this.vMaxX = 5; // Maximum X velocity range for snow
  39. this.vMaxY = 4; // Maximum Y velocity range for snow
  40. this.zIndex = 0; // CSS stacking order applied to each snowflake
  41. // --- "No user-serviceable parts inside" past this point, yadda yadda ---
  42. var storm = this,
  43. features,
  44. // UA sniffing and backCompat rendering mode checks for fixed position, etc.
  45. isIE = navigator.userAgent.match(/msie/i),
  46. isIE6 = navigator.userAgent.match(/msie 6/i),
  47. isMobile = navigator.userAgent.match(/mobile|opera m(ob|in)/i),
  48. isBackCompatIE = (isIE && document.compatMode === 'BackCompat'),
  49. noFixed = (isBackCompatIE || isIE6),
  50. screenX = null, screenX2 = null, screenY = null, scrollY = null, docHeight = null, vRndX = null, vRndY = null,
  51. windOffset = 1,
  52. windMultiplier = 2,
  53. flakeTypes = 6,
  54. fixedForEverything = false,
  55. targetElementIsRelative = false,
  56. opacitySupported = (function(){
  57. try {
  58. document.createElement('div').style.opacity = '0.5';
  59. } catch(e) {
  60. return false;
  61. }
  62. return true;
  63. }()),
  64. didInit = false,
  65. docFrag = document.createDocumentFragment();
  66. features = (function() {
  67. var getAnimationFrame;
  68. /**
  69. * hat tip: paul irish
  70. * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  71. * https://gist.github.com/838785
  72. */
  73. function timeoutShim(callback) {
  74. window.setTimeout(callback, 1000/(storm.animationInterval || 20));
  75. }
  76. var _animationFrame = (window.requestAnimationFrame ||
  77. window.webkitRequestAnimationFrame ||
  78. window.mozRequestAnimationFrame ||
  79. window.oRequestAnimationFrame ||
  80. window.msRequestAnimationFrame ||
  81. timeoutShim);
  82. // apply to window, avoid "illegal invocation" errors in Chrome
  83. getAnimationFrame = _animationFrame ? function() {
  84. return _animationFrame.apply(window, arguments);
  85. } : null;
  86. var testDiv;
  87. testDiv = document.createElement('div');
  88. function has(prop) {
  89. // test for feature support
  90. var result = testDiv.style[prop];
  91. return (result !== undefined ? prop : null);
  92. }
  93. // note local scope.
  94. var localFeatures = {
  95. transform: {
  96. ie: has('-ms-transform'),
  97. moz: has('MozTransform'),
  98. opera: has('OTransform'),
  99. webkit: has('webkitTransform'),
  100. w3: has('transform'),
  101. prop: null // the normalized property value
  102. },
  103. getAnimationFrame: getAnimationFrame
  104. };
  105. localFeatures.transform.prop = (
  106. localFeatures.transform.w3 ||
  107. localFeatures.transform.moz ||
  108. localFeatures.transform.webkit ||
  109. localFeatures.transform.ie ||
  110. localFeatures.transform.opera
  111. );
  112. testDiv = null;
  113. return localFeatures;
  114. }());
  115. this.timer = null;
  116. this.flakes = [];
  117. this.disabled = false;
  118. this.active = false;
  119. this.meltFrameCount = 20;
  120. this.meltFrames = [];
  121. this.setXY = function(o, x, y) {
  122. if (!o) {
  123. return false;
  124. }
  125. if (storm.usePixelPosition || targetElementIsRelative) {
  126. o.style.left = (x - storm.flakeWidth) + 'px';
  127. o.style.top = (y - storm.flakeHeight) + 'px';
  128. } else if (noFixed) {
  129. o.style.right = (100-(x/screenX*100)) + '%';
  130. // avoid creating vertical scrollbars
  131. o.style.top = (Math.min(y, docHeight-storm.flakeHeight)) + 'px';
  132. } else {
  133. if (!storm.flakeBottom) {
  134. // if not using a fixed bottom coordinate...
  135. o.style.right = (100-(x/screenX*100)) + '%';
  136. o.style.bottom = (100-(y/screenY*100)) + '%';
  137. } else {
  138. // absolute top.
  139. o.style.right = (100-(x/screenX*100)) + '%';
  140. o.style.top = (Math.min(y, docHeight-storm.flakeHeight)) + 'px';
  141. }
  142. }
  143. };
  144. this.events = (function() {
  145. var old = (!window.addEventListener && window.attachEvent), slice = Array.prototype.slice,
  146. evt = {
  147. add: (old?'attachEvent':'addEventListener'),
  148. remove: (old?'detachEvent':'removeEventListener')
  149. };
  150. function getArgs(oArgs) {
  151. var args = slice.call(oArgs), len = args.length;
  152. if (old) {
  153. args[1] = 'on' + args[1]; // prefix
  154. if (len > 3) {
  155. args.pop(); // no capture
  156. }
  157. } else if (len === 3) {
  158. args.push(false);
  159. }
  160. return args;
  161. }
  162. function apply(args, sType) {
  163. var element = args.shift(),
  164. method = [evt[sType]];
  165. if (old) {
  166. element[method](args[0], args[1]);
  167. } else {
  168. element[method].apply(element, args);
  169. }
  170. }
  171. function addEvent() {
  172. apply(getArgs(arguments), 'add');
  173. }
  174. function removeEvent() {
  175. apply(getArgs(arguments), 'remove');
  176. }
  177. return {
  178. add: addEvent,
  179. remove: removeEvent
  180. };
  181. }());
  182. function rnd(n,min) {
  183. if (isNaN(min)) {
  184. min = 0;
  185. }
  186. return (Math.random()*n)+min;
  187. }
  188. function plusMinus(n) {
  189. return (parseInt(rnd(2),10)===1?n*-1:n);
  190. }
  191. this.randomizeWind = function() {
  192. var i;
  193. vRndX = plusMinus(rnd(storm.vMaxX,0.2));
  194. vRndY = rnd(storm.vMaxY,0.2);
  195. if (this.flakes) {
  196. for (i=0; i<this.flakes.length; i++) {
  197. if (this.flakes[i].active) {
  198. this.flakes[i].setVelocities();
  199. }
  200. }
  201. }
  202. };
  203. this.scrollHandler = function() {
  204. var i;
  205. // "attach" snowflakes to bottom of window if no absolute bottom value was given
  206. scrollY = (storm.flakeBottom ? 0 : parseInt(window.scrollY || document.documentElement.scrollTop || (noFixed ? document.body.scrollTop : 0), 10));
  207. if (isNaN(scrollY)) {
  208. scrollY = 0; // Netscape 6 scroll fix
  209. }
  210. if (!fixedForEverything && !storm.flakeBottom && storm.flakes) {
  211. for (i=0; i<storm.flakes.length; i++) {
  212. if (storm.flakes[i].active === 0) {
  213. storm.flakes[i].stick();
  214. }
  215. }
  216. }
  217. };
  218. this.resizeHandler = function() {
  219. if (window.innerWidth || window.innerHeight) {
  220. screenX = window.innerWidth - 16 - storm.flakeRightOffset;
  221. screenY = (storm.flakeBottom || window.innerHeight);
  222. } else {
  223. screenX = (document.documentElement.clientWidth || document.body.clientWidth || document.body.scrollWidth) - (!isIE ? 8 : 0) - storm.flakeRightOffset;
  224. screenY = storm.flakeBottom || document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight;
  225. }
  226. docHeight = document.body.offsetHeight;
  227. screenX2 = parseInt(screenX/2,10);
  228. };
  229. this.resizeHandlerAlt = function() {
  230. screenX = storm.targetElement.offsetWidth - storm.flakeRightOffset;
  231. screenY = storm.flakeBottom || storm.targetElement.offsetHeight;
  232. screenX2 = parseInt(screenX/2,10);
  233. docHeight = document.body.offsetHeight;
  234. };
  235. this.freeze = function() {
  236. // pause animation
  237. if (!storm.disabled) {
  238. storm.disabled = 1;
  239. } else {
  240. return false;
  241. }
  242. storm.timer = null;
  243. };
  244. this.resume = function() {
  245. if (storm.disabled) {
  246. storm.disabled = 0;
  247. } else {
  248. return false;
  249. }
  250. storm.timerInit();
  251. };
  252. this.toggleSnow = function() {
  253. if (!storm.flakes.length) {
  254. // first run
  255. storm.start();
  256. } else {
  257. storm.active = !storm.active;
  258. if (storm.active) {
  259. storm.show();
  260. storm.resume();
  261. } else {
  262. storm.stop();
  263. storm.freeze();
  264. }
  265. }
  266. };
  267. this.stop = function() {
  268. var i;
  269. this.freeze();
  270. for (i=0; i<this.flakes.length; i++) {
  271. this.flakes[i].o.style.display = 'none';
  272. }
  273. storm.events.remove(window,'scroll',storm.scrollHandler);
  274. storm.events.remove(window,'resize',storm.resizeHandler);
  275. if (storm.freezeOnBlur) {
  276. if (isIE) {
  277. storm.events.remove(document,'focusout',storm.freeze);
  278. storm.events.remove(document,'focusin',storm.resume);
  279. } else {
  280. storm.events.remove(window,'blur',storm.freeze);
  281. storm.events.remove(window,'focus',storm.resume);
  282. }
  283. }
  284. };
  285. this.show = function() {
  286. var i;
  287. for (i=0; i<this.flakes.length; i++) {
  288. this.flakes[i].o.style.display = 'block';
  289. }
  290. };
  291. this.SnowFlake = function(type,x,y) {
  292. var s = this;
  293. this.type = type;
  294. this.x = x||parseInt(rnd(screenX-20),10);
  295. this.y = (!isNaN(y)?y:-rnd(screenY)-12);
  296. this.vX = null;
  297. this.vY = null;
  298. this.vAmpTypes = [1,1.2,1.4,1.6,1.8]; // "amplification" for vX/vY (based on flake size/type)
  299. this.vAmp = this.vAmpTypes[this.type] || 1;
  300. this.melting = false;
  301. this.meltFrameCount = storm.meltFrameCount;
  302. this.meltFrames = storm.meltFrames;
  303. this.meltFrame = 0;
  304. this.twinkleFrame = 0;
  305. this.active = 1;
  306. this.fontSize = (10+(this.type/5)*10);
  307. this.o = document.createElement('div');
  308. this.o.innerHTML = storm.snowCharacter;
  309. if (storm.className) {
  310. this.o.setAttribute('class', storm.className);
  311. }
  312. this.o.style.color = storm.snowColor;
  313. this.o.style.position = (fixedForEverything?'fixed':'absolute');
  314. if (storm.useGPU && features.transform.prop) {
  315. // GPU-accelerated snow.
  316. this.o.style[features.transform.prop] = 'translate3d(0px, 0px, 0px)';
  317. }
  318. this.o.style.width = storm.flakeWidth+'px';
  319. this.o.style.height = storm.flakeHeight+'px';
  320. this.o.style.fontFamily = 'arial,verdana';
  321. this.o.style.cursor = 'default';
  322. this.o.style.overflow = 'hidden';
  323. this.o.style.fontWeight = 'normal';
  324. this.o.style.zIndex = storm.zIndex;
  325. docFrag.appendChild(this.o);
  326. this.refresh = function() {
  327. if (isNaN(s.x) || isNaN(s.y)) {
  328. // safety check
  329. return false;
  330. }
  331. storm.setXY(s.o, s.x, s.y);
  332. };
  333. this.stick = function() {
  334. if (noFixed || (storm.targetElement !== document.documentElement && storm.targetElement !== document.body)) {
  335. s.o.style.top = (screenY+scrollY-storm.flakeHeight)+'px';
  336. } else if (storm.flakeBottom) {
  337. s.o.style.top = storm.flakeBottom+'px';
  338. } else {
  339. s.o.style.display = 'none';
  340. s.o.style.top = 'auto';
  341. s.o.style.bottom = '0%';
  342. s.o.style.position = 'fixed';
  343. s.o.style.display = 'block';
  344. }
  345. };
  346. this.vCheck = function() {
  347. if (s.vX>=0 && s.vX<0.2) {
  348. s.vX = 0.2;
  349. } else if (s.vX<0 && s.vX>-0.2) {
  350. s.vX = -0.2;
  351. }
  352. if (s.vY>=0 && s.vY<0.2) {
  353. s.vY = 0.2;
  354. }
  355. };
  356. this.move = function() {
  357. var vX = s.vX*windOffset, yDiff;
  358. s.x += vX;
  359. s.y += (s.vY*s.vAmp);
  360. if (s.x >= screenX || screenX-s.x < storm.flakeWidth) { // X-axis scroll check
  361. s.x = 0;
  362. } else if (vX < 0 && s.x-storm.flakeLeftOffset < -storm.flakeWidth) {
  363. s.x = screenX-storm.flakeWidth-1; // flakeWidth;
  364. }
  365. s.refresh();
  366. yDiff = screenY+scrollY-s.y+storm.flakeHeight;
  367. if (yDiff<storm.flakeHeight) {
  368. s.active = 0;
  369. if (storm.snowStick) {
  370. s.stick();
  371. } else {
  372. s.recycle();
  373. }
  374. } else {
  375. if (storm.useMeltEffect && s.active && s.type < 3 && !s.melting && Math.random()>0.998) {
  376. // ~1/1000 chance of melting mid-air, with each frame
  377. s.melting = true;
  378. s.melt();
  379. // only incrementally melt one frame
  380. // s.melting = false;
  381. }
  382. if (storm.useTwinkleEffect) {
  383. if (s.twinkleFrame < 0) {
  384. if (Math.random() > 0.97) {
  385. s.twinkleFrame = parseInt(Math.random() * 8, 10);
  386. }
  387. } else {
  388. s.twinkleFrame--;
  389. if (!opacitySupported) {
  390. s.o.style.visibility = (s.twinkleFrame && s.twinkleFrame % 2 === 0 ? 'hidden' : 'visible');
  391. } else {
  392. s.o.style.opacity = (s.twinkleFrame && s.twinkleFrame % 2 === 0 ? 0 : 1);
  393. }
  394. }
  395. }
  396. }
  397. };
  398. this.animate = function() {
  399. // main animation loop
  400. // move, check status, die etc.
  401. s.move();
  402. };
  403. this.setVelocities = function() {
  404. s.vX = vRndX+rnd(storm.vMaxX*0.12,0.1);
  405. s.vY = vRndY+rnd(storm.vMaxY*0.12,0.1);
  406. };
  407. this.setOpacity = function(o,opacity) {
  408. if (!opacitySupported) {
  409. return false;
  410. }
  411. o.style.opacity = opacity;
  412. };
  413. this.melt = function() {
  414. if (!storm.useMeltEffect || !s.melting) {
  415. s.recycle();
  416. } else {
  417. if (s.meltFrame < s.meltFrameCount) {
  418. s.setOpacity(s.o,s.meltFrames[s.meltFrame]);
  419. s.o.style.fontSize = s.fontSize-(s.fontSize*(s.meltFrame/s.meltFrameCount))+'px';
  420. s.o.style.lineHeight = storm.flakeHeight+2+(storm.flakeHeight*0.75*(s.meltFrame/s.meltFrameCount))+'px';
  421. s.meltFrame++;
  422. } else {
  423. s.recycle();
  424. }
  425. }
  426. };
  427. this.recycle = function() {
  428. s.o.style.display = 'none';
  429. s.o.style.position = (fixedForEverything?'fixed':'absolute');
  430. s.o.style.bottom = 'auto';
  431. s.setVelocities();
  432. s.vCheck();
  433. s.meltFrame = 0;
  434. s.melting = false;
  435. s.setOpacity(s.o,1);
  436. s.o.style.padding = '0px';
  437. s.o.style.margin = '0px';
  438. s.o.style.fontSize = s.fontSize+'px';
  439. s.o.style.lineHeight = (storm.flakeHeight+2)+'px';
  440. s.o.style.textAlign = 'center';
  441. s.o.style.verticalAlign = 'baseline';
  442. s.x = parseInt(rnd(screenX-storm.flakeWidth-20),10);
  443. s.y = parseInt(rnd(screenY)*-1,10)-storm.flakeHeight;
  444. s.refresh();
  445. s.o.style.display = 'block';
  446. s.active = 1;
  447. };
  448. this.recycle(); // set up x/y coords etc.
  449. this.refresh();
  450. };
  451. this.snow = function() {
  452. var active = 0, flake = null, i, j;
  453. for (i=0, j=storm.flakes.length; i<j; i++) {
  454. if (storm.flakes[i].active === 1) {
  455. storm.flakes[i].move();
  456. active++;
  457. }
  458. if (storm.flakes[i].melting) {
  459. storm.flakes[i].melt();
  460. }
  461. }
  462. if (active<storm.flakesMaxActive) {
  463. flake = storm.flakes[parseInt(rnd(storm.flakes.length),10)];
  464. if (flake.active === 0) {
  465. flake.melting = true;
  466. }
  467. }
  468. if (storm.timer) {
  469. features.getAnimationFrame(storm.snow);
  470. }
  471. };
  472. this.mouseMove = function(e) {
  473. if (!storm.followMouse) {
  474. return true;
  475. }
  476. var x = parseInt(e.clientX,10);
  477. if (x<screenX2) {
  478. windOffset = -windMultiplier+(x/screenX2*windMultiplier);
  479. } else {
  480. x -= screenX2;
  481. windOffset = (x/screenX2)*windMultiplier;
  482. }
  483. };
  484. this.createSnow = function(limit,allowInactive) {
  485. var i;
  486. for (i=0; i<limit; i++) {
  487. storm.flakes[storm.flakes.length] = new storm.SnowFlake(parseInt(rnd(flakeTypes),10));
  488. if (allowInactive || i>storm.flakesMaxActive) {
  489. storm.flakes[storm.flakes.length-1].active = -1;
  490. }
  491. }
  492. storm.targetElement.appendChild(docFrag);
  493. };
  494. this.timerInit = function() {
  495. storm.timer = true;
  496. storm.snow();
  497. };
  498. this.init = function() {
  499. var i;
  500. for (i=0; i<storm.meltFrameCount; i++) {
  501. storm.meltFrames.push(1-(i/storm.meltFrameCount));
  502. }
  503. storm.randomizeWind();
  504. storm.createSnow(storm.flakesMax); // create initial batch
  505. storm.events.add(window,'resize',storm.resizeHandler);
  506. storm.events.add(window,'scroll',storm.scrollHandler);
  507. if (storm.freezeOnBlur) {
  508. if (isIE) {
  509. storm.events.add(document,'focusout',storm.freeze);
  510. storm.events.add(document,'focusin',storm.resume);
  511. } else {
  512. storm.events.add(window,'blur',storm.freeze);
  513. storm.events.add(window,'focus',storm.resume);
  514. }
  515. }
  516. storm.resizeHandler();
  517. storm.scrollHandler();
  518. if (storm.followMouse) {
  519. storm.events.add(isIE?document:window,'mousemove',storm.mouseMove);
  520. }
  521. storm.animationInterval = Math.max(20,storm.animationInterval);
  522. storm.timerInit();
  523. };
  524. this.start = function(bFromOnLoad) {
  525. if (!didInit) {
  526. didInit = true;
  527. } else if (bFromOnLoad) {
  528. // already loaded and running
  529. return true;
  530. }
  531. if (typeof storm.targetElement === 'string') {
  532. var targetID = storm.targetElement;
  533. storm.targetElement = document.getElementById(targetID);
  534. if (!storm.targetElement) {
  535. throw new Error('Snowstorm: Unable to get targetElement "'+targetID+'"');
  536. }
  537. }
  538. if (!storm.targetElement) {
  539. storm.targetElement = (document.body || document.documentElement);
  540. }
  541. if (storm.targetElement !== document.documentElement && storm.targetElement !== document.body) {
  542. // re-map handler to get element instead of screen dimensions
  543. storm.resizeHandler = storm.resizeHandlerAlt;
  544. //and force-enable pixel positioning
  545. storm.usePixelPosition = true;
  546. }
  547. storm.resizeHandler(); // get bounding box elements
  548. storm.usePositionFixed = (storm.usePositionFixed && !noFixed && !storm.flakeBottom); // whether or not position:fixed is to be used
  549. if (window.getComputedStyle) {
  550. // attempt to determine if body or user-specified snow parent element is relatlively-positioned.
  551. try {
  552. targetElementIsRelative = (window.getComputedStyle(storm.targetElement, null).getPropertyValue('position') === 'relative');
  553. } catch(e) {
  554. // oh well
  555. targetElementIsRelative = false;
  556. }
  557. }
  558. fixedForEverything = storm.usePositionFixed;
  559. if (screenX && screenY && !storm.disabled) {
  560. storm.init();
  561. storm.active = true;
  562. }
  563. };
  564. function doDelayedStart() {
  565. window.setTimeout(function() {
  566. storm.start(true);
  567. }, 20);
  568. // event cleanup
  569. storm.events.remove(isIE?document:window,'mousemove',doDelayedStart);
  570. }
  571. function doStart() {
  572. if (!storm.excludeMobile || !isMobile) {
  573. doDelayedStart();
  574. }
  575. // event cleanup
  576. storm.events.remove(window, 'load', doStart);
  577. }
  578. // hooks for starting the snow
  579. if (storm.autoStart) {
  580. storm.events.add(window, 'load', doStart, false);
  581. }
  582. return this;
  583. }(window, document));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement