/trunk/src/snowfall.jquery.js

http://jsnowfall.googlecode.com/ · JavaScript · 300 lines · 177 code · 36 blank · 87 comment · 40 complexity · 683457f2f7772df44aa2dfe1785fe5f5 MD5 · raw file

  1. /* Snowfall jquery plugin
  2. ====================================================================
  3. LICENSE
  4. ====================================================================
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. Version 1.5 Oct 5th 2011
  15. Added collecting snow! Uses the canvas element to collect snow. In order to initialize snow collection use the following
  16. $(document).snowfall({collection : 'element'});
  17. element = any valid jquery selector.
  18. The plugin then creates a canvas above every element that matches the selector, and collects the snow. If there are a varrying amount of elements the
  19. flakes get assigned a random one on start they will collide.
  20. Version 1.4 Dec 8th 2010
  21. Fixed issues (I hope) with scroll bars flickering due to snow going over the edge of the screen.
  22. Added round snowflakes via css, will not work for any version of IE. - Thanks to Luke Barker of http://www.infinite-eye.com/
  23. Added shadows as an option via css again will not work with IE. The idea behind shadows, is to show flakes on lighter colored web sites - Thanks Yutt
  24. Version 1.3.1 Nov 25th 2010
  25. Updated script that caused flakes not to show at all if plugin was initialized with no options, also added the fixes that Han Bongers suggested
  26. Developed by Jason Brown for any bugs or questions email me at loktar69@hotmail
  27. info on the plugin is located on Somethinghitme.com
  28. values for snow options are
  29. flakeCount,
  30. flakeColor,
  31. flakeIndex,
  32. minSize,
  33. maxSize,
  34. minSpeed,
  35. maxSpeed,
  36. round, true or false, makes the snowflakes rounded if the browser supports it.
  37. shadow true or false, gives the snowflakes a shadow if the browser supports it.
  38. Example Usage :
  39. $(document).snowfall({flakeCount : 100, maxSpeed : 10});
  40. -or-
  41. $('#element').snowfall({flakeCount : 800, maxSpeed : 5, maxSize : 5});
  42. -or with defaults-
  43. $(document).snowfall();
  44. - To clear -
  45. $('#element').snowfall('clear');
  46. */
  47. (function($){
  48. $.snowfall = function(element, options){
  49. var defaults = {
  50. flakeCount : 35,
  51. flakeColor : '#ffffff',
  52. flakeIndex: 999999,
  53. minSize : 1,
  54. maxSize : 2,
  55. minSpeed : 1,
  56. maxSpeed : 5,
  57. round : false,
  58. shadow : false,
  59. collection : false,
  60. collectionHeight : 40
  61. },
  62. options = $.extend(defaults, options),
  63. random = function random(min, max){
  64. return Math.round(min + Math.random()*(max-min));
  65. };
  66. $(element).data("snowfall", this);
  67. // Snow flake object
  68. function Flake(_x, _y, _size, _speed, _id)
  69. {
  70. // Flake properties
  71. this.id = _id;
  72. this.x = _x;
  73. this.y = _y;
  74. this.size = _size;
  75. this.speed = _speed;
  76. this.step = 0;
  77. this.stepSize = random(1,10) / 100;
  78. if(options.collection){
  79. this.target = canvasCollection[random(0,canvasCollection.length-1)];
  80. }
  81. var flakeMarkup = $(document.createElement("div")).attr({'class': 'snowfall-flakes', 'id' : 'flake-' + this.id}).css({'width' : this.size, 'height' : this.size, 'background' : options.flakeColor, 'position' : 'absolute', 'top' : this.y, 'left' : this.x, 'fontSize' : 0, 'zIndex' : options.flakeIndex});
  82. if($(element).get(0).tagName === $(document).get(0).tagName){
  83. $('body').append(flakeMarkup);
  84. element = $('body');
  85. }else{
  86. $(element).append(flakeMarkup);
  87. }
  88. this.element = document.getElementById('flake-' + this.id);
  89. // Update function, used to update the snow flakes, and checks current snowflake against bounds
  90. this.update = function(){
  91. this.y += this.speed;
  92. if(this.y > (elHeight) - (this.size + 6)){
  93. this.reset();
  94. }
  95. this.element.style.top = this.y + 'px';
  96. this.element.style.left = this.x + 'px';
  97. this.step += this.stepSize;
  98. this.x += Math.cos(this.step);
  99. // Pileup check
  100. if(options.collection){
  101. if(this.x > this.target.x && this.x < this.target.width + this.target.x && this.y > this.target.y && this.y < this.target.height + this.target.y){
  102. var ctx = this.target.element.getContext("2d"),
  103. curX = this.x - this.target.x,
  104. curY = this.y - this.target.y,
  105. colData = this.target.colData;
  106. if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] !== undefined || curY+this.speed+this.size > this.target.height){
  107. if(curY+this.speed+this.size > this.target.height){
  108. while(curY+this.speed+this.size > this.target.height && this.speed > 0){
  109. this.speed *= .5;
  110. }
  111. ctx.fillStyle = "#fff";
  112. if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] == undefined){
  113. colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] = 1;
  114. ctx.fillRect(curX, (curY)+this.speed+this.size, this.size, this.size);
  115. }else{
  116. colData[parseInt(curX)][parseInt(curY+this.speed)] = 1;
  117. ctx.fillRect(curX, curY+this.speed, this.size, this.size);
  118. }
  119. this.reset();
  120. }else{
  121. // flow to the sides
  122. this.speed = 1;
  123. this.stepSize = 0;
  124. if(parseInt(curX)+1 < this.target.width && colData[parseInt(curX)+1][parseInt(curY)+1] == undefined ){
  125. // go left
  126. this.x++;
  127. }else if(parseInt(curX)-1 > 0 && colData[parseInt(curX)-1][parseInt(curY)+1] == undefined ){
  128. // go right
  129. this.x--;
  130. }else{
  131. //stop
  132. ctx.fillStyle = "#fff";
  133. ctx.fillRect(curX, curY, this.size, this.size);
  134. colData[parseInt(curX)][parseInt(curY)] = 1;
  135. this.reset();
  136. }
  137. }
  138. }
  139. }
  140. }
  141. if(this.x > (elWidth) - widthOffset || this.x < widthOffset){
  142. this.reset();
  143. }
  144. }
  145. // Resets the snowflake once it reaches one of the bounds set
  146. this.reset = function(){
  147. this.y = 0;
  148. this.x = random(widthOffset, elWidth - widthOffset);
  149. this.stepSize = random(1,10) / 100;
  150. this.size = random((options.minSize * 100), (options.maxSize * 100)) / 100;
  151. this.speed = random(options.minSpeed, options.maxSpeed);
  152. }
  153. }
  154. // Private vars
  155. var flakes = [],
  156. flakeId = 0,
  157. i = 0,
  158. elHeight = $(element).height(),
  159. elWidth = $(element).width(),
  160. widthOffset = 0,
  161. snowTimeout = 0;
  162. // Collection Piece ******************************
  163. if(options.collection !== false){
  164. var testElem = document.createElement('canvas');
  165. if(!!(testElem.getContext && testElem.getContext('2d'))){
  166. var canvasCollection = [],
  167. elements = $(options.collection),
  168. collectionHeight = options.collectionHeight;
  169. for(var i =0; i < elements.length; i++){
  170. var bounds = elements[i].getBoundingClientRect(),
  171. canvas = document.createElement('canvas'),
  172. collisionData = [];
  173. if(bounds.top-collectionHeight > 0){
  174. document.body.appendChild(canvas);
  175. canvas.style.position = 'absolute';
  176. canvas.height = collectionHeight;
  177. canvas.width = bounds.width;
  178. canvas.style.left = bounds.left;
  179. canvas.style.top = bounds.top-collectionHeight;
  180. for(var w = 0; w < bounds.width; w++){
  181. collisionData[w] = [];
  182. }
  183. canvasCollection.push({element :canvas, x : bounds.left, y : bounds.top-collectionHeight, width : bounds.width, height: collectionHeight, colData : collisionData});
  184. }
  185. }
  186. }else{
  187. // Canvas element isnt supported
  188. options.collection = false;
  189. }
  190. }
  191. // ************************************************
  192. // This will reduce the horizontal scroll bar from displaying, when the effect is applied to the whole page
  193. if($(element).get(0).tagName === $(document).get(0).tagName){
  194. widthOffset = 25;
  195. }
  196. // Bind the window resize event so we can get the innerHeight again
  197. $(window).bind("resize", function(){
  198. elHeight = $(element).height();
  199. elWidth = $(element).width();
  200. });
  201. // initialize the flakes
  202. for(i = 0; i < options.flakeCount; i+=1){
  203. flakeId = flakes.length;
  204. flakes.push(new Flake(random(widthOffset,elWidth - widthOffset), random(0, elHeight), random((options.minSize * 100), (options.maxSize * 100)) / 100, random(options.minSpeed, options.maxSpeed), flakeId));
  205. }
  206. // This adds the style to make the snowflakes round via border radius property
  207. if(options.round){
  208. $('.snowfall-flakes').css({'-moz-border-radius' : options.maxSize, '-webkit-border-radius' : options.maxSize, 'border-radius' : options.maxSize});
  209. }
  210. // This adds shadows just below the snowflake so they pop a bit on lighter colored web pages
  211. if(options.shadow){
  212. $('.snowfall-flakes').css({'-moz-box-shadow' : '1px 1px 1px #555', '-webkit-box-shadow' : '1px 1px 1px #555', 'box-shadow' : '1px 1px 1px #555'});
  213. }
  214. // this controls flow of the updating snow
  215. function snow(){
  216. for( i = 0; i < flakes.length; i += 1){
  217. flakes[i].update();
  218. }
  219. snowTimeout = setTimeout(function(){snow()}, 30);
  220. }
  221. snow();
  222. // Public Methods
  223. // clears the snowflakes
  224. this.clear = function(){
  225. $(element).children('.snowfall-flakes').remove();
  226. flakes = [];
  227. clearTimeout(snowTimeout);
  228. };
  229. };
  230. // Initialize the options and the plugin
  231. $.fn.snowfall = function(options){
  232. if(typeof(options) == "object" || options == undefined){
  233. return this.each(function(i){
  234. (new $.snowfall(this, options));
  235. });
  236. }else if (typeof(options) == "string") {
  237. return this.each(function(i){
  238. var snow = $(this).data('snowfall');
  239. if(snow){
  240. snow.clear();
  241. }
  242. });
  243. }
  244. };
  245. })(jQuery);