首页 > 语言 > JavaScript > 正文

javascript转换静态图片,增加粒子动画效果

2024-05-06 16:20:57
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了javascript转换静态图片,增加粒子动画效果,非常的炫酷,需要的朋友可以参考下

使用getImageData接口获取图片的像素点,然后基于像素点实现动画效果,封装成一个简单的lib

 

 
  1. <!DOCTYPE html> 
  2. <html> 
  3. <head> 
  4. <title>particle image</title> 
  5. <meta charset="utf-8" /> 
  6. <style> 
  7. #logo { 
  8. margin-left:20px; 
  9. margin-top:20px; 
  10. width:160px; 
  11. height:48px; 
  12. background:url('./images/logo.png'); 
  13. /*border: 1px solid red;*/ 
  14. } 
  15. </style> 
  16. <script type="text/javascript" src="ParticleImage.js"></script> 
  17. <script> 
  18. window.onload = function() { 
  19. ParticleImage.create("logo", "./images/logo.png", "fast"); 
  20. }; 
  21. </script> 
  22. </head> 
  23. <body> 
  24. <div id="logo"></div> 
  25. </body> 
  26. </html> 

ParticleImage.js

 

 
  1. /* 
  2. The MIT License (MIT) 
  3.  
  4. Copyright (c) 2015 arest 
  5.  
  6. Permission is hereby granted, free of charge, to any person obtaining a copy of 
  7. this software and associated documentation files (the "Software"), to deal in 
  8. the Software without restriction, including without limitation the rights to 
  9. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 
  10. the Software, and to permit persons to whom the Software is furnished to do so, 
  11. subject to the following conditions: 
  12.  
  13. The above copyright notice and this permission notice shall be included in all 
  14. copies or substantial portions of the Software. 
  15.  
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
  18. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
  19. COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
  20. IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
  21. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
  22. */ 
  23.  
  24. /** 
  25. * Add particle animation for image 
  26. * usage: 
  27. <script type="text/javascript" src="ParticleImage.js"></script> 
  28. <script> 
  29. window.onload = function() { 
  30. // be sure to use image file in your own server (prevent CORS issue) 
  31. ParticleImage.create("logo", "logo_s2.png", "fast"); 
  32. }; 
  33. </script> 
  34. // in html file 
  35. <div id="logo"></div> 
  36. // you can set default background image as usual 
  37. #logo { 
  38. margin-left:20px; 
  39. margin-top:20px; 
  40. width:160px; 
  41. height:48px; 
  42. background:url('logo_s2.png'); 
  43. } 
  44. * 
  45. * @author tianx.qin (rushi_wowen@163.com) 
  46. * @file ParticleImage.js 
  47. * @version 0.9 
  48. */ 
  49. var ParticleImage = (function(window) { 
  50. var container = null, canvas = null; 
  51. var ctx = null, _spirit = [], timer = null, 
  52. cw = 0, ch = 0, // container width/height 
  53. iw = 0, ih = 0, // image width/height 
  54. mx = 0, my = 0, // mouse position 
  55. bMove = true, 
  56. MOVE_SPAN = 4, DEFAULT_ALPHA = 100, 
  57. speed = 100, S = {"fast":10, "mid":100, "low":300}, 
  58. ALPHA = 255 * 255; 
  59.  
  60. // spirit class 
  61. var Spirit = function(data) { 
  62. this.orginal = { 
  63. pos: data.pos, 
  64. x : data.x, y : data.y, 
  65. r : data.r, g : data.g, b : data.b, a : data.a 
  66. }; 
  67. // change state, for animation 
  68. this.current = { 
  69. x : data.x, 
  70. y : data.y, 
  71. a : data.a 
  72. }; 
  73. }; 
  74.  
  75. /** 
  76. * move spirit to original position 
  77. */ 
  78. Spirit.prototype.move = function() { 
  79. var cur = this.current, orig = this.orginal; 
  80. if ((cur.x === orig.x) && (cur.y === orig.y)) { 
  81. //console.log("don't move:" + cur.y); 
  82. return false; 
  83. } 
  84. //console.log("move:" + cur.y); 
  85. var rand = 1 + Math.round(MOVE_SPAN * Math.random()); 
  86. var offsetX = cur.x - orig.x, 
  87. offsetY = cur.y - orig.y; 
  88. var rad = offsetX == 0 ? 0 : offsetY / offsetX; 
  89. var xSpan = cur.x < orig.x ? rand : cur.x > orig.x ? -rand : 0; 
  90. cur.x += xSpan; 
  91. var tempY = xSpan == 0 ? Math.abs(rand) : Math.abs(Math.round(rad * xSpan)); 
  92. var ySpan = offsetY < 0 ? tempY : offsetY > 0 ? -tempY : 0; 
  93. cur.y += ySpan; 
  94. cur.a = ((cur.x === orig.x) && (cur.y === orig.y)) ? orig.a : DEFAULT_ALPHA; 
  95. return true; 
  96. }; 
  97.  
  98. /** 
  99. * set random position 
  100. */ 
  101. Spirit.prototype.random = function(width, height) { 
  102. var cur = this.current; 
  103. cur.x = width + Math.round(width * 2 * Math.random()); 
  104. this.current.y = height + Math.round(height * 2 * Math.random()); 
  105. }; 
  106.  
  107. /** 
  108. * set random positions for all spirits 
  109. */ 
  110. var _disorder = function() { 
  111. var len = _spirit.length; 
  112. for (var i = 0; i < len; i++) { 
  113. _spirit[i].random(cw, ch); 
  114. } 
  115. }; 
  116.  
  117. /** 
  118. * start to move spirit 
  119. */ 
  120. var _move = function() { 
  121. var sprt = _spirit; 
  122. var len = sprt.length; 
  123. var isMove = false; // whether need to move 
  124. for (var i = 0; i < len; i++) { 
  125. if (sprt[i].move()) { 
  126. isMove = true; 
  127. } 
  128. } 
  129. isMove ? _redraw() : _stopTimer(); 
  130. }; 
  131.  
  132. /** 
  133. * redraw all spirits while animating 
  134. */ 
  135. var _redraw = function() { 
  136. var imgDataObj = ctx.createImageData(iw, ih); 
  137. var imgData = imgDataObj.data; 
  138. var sprt = _spirit; 
  139. var len = sprt.length; 
  140. //console.log("redraw image : " + len); 
  141. for (var i = 0; i < len; i++) { 
  142. var temp = sprt[i]; 
  143. //console.log("item : " + JSON.stringify(temp)); 
  144. var orig = temp.orginal; 
  145. var cur = temp.current; 
  146. var pos = (cur.y * iw + cur.x) * 4; 
  147. imgData[pos] = orig.r; 
  148. imgData[pos + 1] = orig.g; 
  149. imgData[pos + 2] = orig.b; 
  150. imgData[pos + 3] = cur.a; 
  151. } 
  152. ctx.putImageData(imgDataObj, 0, 0); 
  153. }; 
  154.  
  155. /** 
  156. * add mousemove/mouseclick event 
  157. */ 
  158. var _addMouseEvent = function(c) { 
  159. c.addEventListener("mouseenter", function(e) { 
  160. //console.log("e.y:" + e.clientY + ", " + container.offsetTop); 
  161. _startTimer(); 
  162. }); 
  163. c.addEventListener("click", function() { 
  164. // disorder all spirits and start animation 
  165. _startTimer(); 
  166. }); 
  167. }; 
  168.  
  169. /** 
  170. * calculate all pixels of the logo image 
  171. */ 
  172. var _checkImage = function(imgUrl, callback) { 
  173. // var tempCanvas = document.getElementById("temp"); 
  174. //canvas.width = width; 
  175. //canvas.height = height; 
  176.  
  177. var proc = function(image) { 
  178. var w = image.width, h = image.height; 
  179. iw = w, ih = h; 
  180. //console.log("proc image " + image + "," + w + "," + h); 
  181. canvas = _createCanvas(); 
  182. // hide container background 
  183. container.style.backgroundPosition = (-w) + "px"; 
  184. container.style.backgroundRepeat = "no-repeat"; 
  185. ctx.drawImage(image, 0, 0); 
  186. // this may cause security error for CORS issue 
  187. try { 
  188. var imgData = ctx.getImageData(0, 0, w, h); 
  189. var arrData = imgData.data; 
  190. for (var i = 0; i < arrData.length; i += 4) { 
  191. var r = arrData[i], g = arrData[i + 1], b = arrData[i + 2], a = arrData[i + 3]; 
  192. if (r > 0 || g > 0 || b > 0 || a > 0) { 
  193. var pos = i / 4; 
  194. _spirit.push(new Spirit({ 
  195. x : pos % w, y : Math.floor(pos / w),  
  196. r : r, g : g, b : b, a : a 
  197. })); 
  198. } 
  199. } 
  200. return true; 
  201. } catch (e) { 
  202. // do nothing 
  203. return false; 
  204. } 
  205. //return out; 
  206. }; 
  207.  
  208. var img = new Image(); 
  209. img.src = imgUrl; 
  210. if (img.complete || img.complete === undefined) { 
  211. proc(img) && callback && callback(); 
  212. } else { 
  213. img.onload = function() { 
  214. proc(img) && callback && callback(); 
  215. }; 
  216. } 
  217. }; 
  218.  
  219. // use "requestAnimationFrame" to create a timer, need browser support 
  220. var _timer = function(func, dur) { 
  221. //console.log("speed is " + dur); 
  222. var timeLast = null; 
  223. var bStop = false; 
  224. var bRunning = false; // prevent running more than once 
  225. var _start = function() { 
  226. if (func) { 
  227. if (! timeLast) { 
  228. timeLast = Date.now(); 
  229. func(); 
  230. } else { 
  231. var current = Date.now(); 
  232. if (current - timeLast >= dur) { 
  233. timeLast = current; 
  234. func(); 
  235. } 
  236. } 
  237. } 
  238.  
  239. if (bStop) { 
  240. return; 
  241. } 
  242. requestAnimationFrame(_start); 
  243. }; 
  244.  
  245. var _stop = function() { 
  246. bStop = true; 
  247. }; 
  248.  
  249. return { 
  250. start : function() { 
  251. if (bRunning) { 
  252. //console.log("already running.."); 
  253. return; 
  254. } 
  255. //console.log("start running.."); 
  256. bRunning = true; 
  257. bStop = false; 
  258. _disorder(); 
  259. _start(); 
  260. }, 
  261. stop : function() { 
  262. _stop(); 
  263. bRunning = false; 
  264. } 
  265. }; 
  266. }; 
  267.  
  268. var _startTimer = function() { 
  269. if (! timer) { 
  270. timer = _timer(function() { 
  271. bMove && _move(); 
  272. }, speed); 
  273. } 
  274. timer.start(); 
  275. }; 
  276.  
  277. var _stopTimer = function() { 
  278. timer && timer.stop(); 
  279. }; 
  280.  
  281. /** 
  282. * start process 
  283. */ 
  284. var _create = function(imgUrl) { 
  285. _checkImage(imgUrl, function() { 
  286. //_createSpirits(); 
  287. _addMouseEvent(canvas); 
  288. //_startTimer(); 
  289. }); 
  290. }; 
  291.  
  292. var _setSpeed = function(s) { 
  293. S[s] && (speed = S[s]); 
  294. }; 
  295.  
  296. /** 
  297. * check whether browser supports canvas 
  298. */ 
  299. var _support = function() { 
  300. try { 
  301. document.createElement("canvas").getContext("2d"); 
  302. return true; 
  303. } catch (e) { 
  304. return false; 
  305. } 
  306. }; 
  307.  
  308. /** 
  309. * create a canvas element 
  310. */ 
  311. var _createCanvas = function() { 
  312. var cav = document.createElement("canvas"); 
  313. cav.width = iw; 
  314. cav.height = ih; 
  315. container.appendChild(cav); 
  316. ctx = cav.getContext("2d"); 
  317. return cav; 
  318. }; 
  319.  
  320. /** 
  321. * initialize container params 
  322. */ 
  323. var _init = function(c, s) { 
  324. if ((! c) || (! _support())) { // DIV id doesn't exist 
  325. return false; 
  326. } 
  327. container = c; 
  328. cw = c.clientWidth; 
  329. ch = c.clientHeight; 
  330. s && _setSpeed(s); 
  331. return true; 
  332. }; 
  333.  
  334. /** 
  335. * export 
  336. */ 
  337. return { 
  338. "create" : function(cId, imgUrl, s) { // user can set move speed by 's'['fast','mid','low'] 
  339. _init(document.getElementById(cId), s) && _create(imgUrl); 
  340. } 
  341. }; 
  342. })(window); 

以上所述就是本文的全部内容了,希望大家能够喜欢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选