如何在HTML CSS JS制作网页中鼠标拖拽粒子效果动画背景cid1146

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>DaisyJS: Particle System Example</title>
  5. <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
  6. <style>
  7. body {
  8. background-image:linear-gradient(rgba(193, 35, 35, 0.71),rgba(32, 39, 216, 0.71)),url(one.png) !important;
  9. background-size: cover;
  10. }
  11. #carbonads a{color:#fff;text-decoration:none}#carbonads a:hover{color:#fff}
  12. /**
  13. * DaisyJS Demo Styles
  14. * by Waren Gonzaga
  15. */
  16. * {
  17. -webkit-box-sizing: border-box;
  18. -moz-box-sizing: border-box;
  19. box-sizing: border-box;
  20. }
  21. html, body {
  22. width: 100%;
  23. height: 100%;
  24. overflow: hidden;
  25. }
  26. body {
  27. font-family: 'Poppins', sans-serif;
  28. color: #fff;
  29. line-height: 1.3;
  30. -webkit-font-smoothing: antialiased;
  31. }
  32. #momoland {
  33. width: 100%;
  34. height: 100%;
  35. overflow: hidden;
  36. }
  37. .wrapper {
  38. position: absolute;
  39. left: 0;
  40. top: 15%;
  41. padding: 0 20px;
  42. width: 100%;
  43. text-align: center;
  44. }
  45. .wrapper > img {
  46. width: 200px;
  47. height: auto;
  48. }
  49. h1 {
  50. color: #fff;
  51. font-size: 100px;
  52. font-family: 'Poppins', sans-serif;
  53. font-weight: 800;
  54. margin-bottom: -10px;
  55. letter-spacing: 2px;
  56. }
  57. p{
  58. width: 39%;
  59. margin: 0 auto;
  60. line-height: 24px;
  61. }
  62. .btn{
  63. padding: 15px 40px;
  64. background: transparent;
  65. color: white;
  66. font-size: 19px;
  67. cursor: pointer;
  68. border-radius: 50px;
  69. outline: none;
  70. border: 2px solid white;
  71. font-family: 'Poppins', sans-serif;
  72. transition: all 0.5s ease-in-out;
  73. }
  74. .btn:hover{
  75. background: white;
  76. color: black;
  77. }
  78. </style>
  79. </head>
  80. <body>
  81. <div id="momoland">
  82. <div class="wrapper">
  83. <br><br><br>
  84. <div id="carbon-block"></div>
  85. <div>
  86. </div>
  87. </div>
  88. </div>
  89. <script src="daisy.js" defer></script>
  90. <script type="text/javascript">
  91. document.addEventListener('DOMContentLoaded', function () {
  92. daisyjs(document.getElementById('momoland'), {
  93. dotColor: '#fff',
  94. lineColor: '#ddd'
  95. });
  96. }, false);
  97. </script>
  98. </body>
  99. </html>
<!doctype html>
<html>
<head> 
<title>DaisyJS: Particle System Example</title>
   
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    
        <style>
body {
  background-image:linear-gradient(rgba(193, 35, 35, 0.71),rgba(32, 39, 216, 0.71)),url(one.png) !important;
    
    background-size: cover;
  
    
}
#carbonads a{color:#fff;text-decoration:none}#carbonads a:hover{color:#fff}
            
             

/**  
 * DaisyJS Demo Styles
 * by Waren Gonzaga
 */

* {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

body {
 
  font-family: 'Poppins', sans-serif;
  color: #fff;
  line-height: 1.3;
  -webkit-font-smoothing: antialiased;
}

#momoland {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.wrapper {
    position: absolute;
    left: 0;
    top: 15%;
    padding: 0 20px;
    width: 100%;
    text-align: center;
}

.wrapper > img {
    width: 200px;
    height: auto;
}

h1 {
    color: #fff;
    font-size: 100px;
    font-family: 'Poppins', sans-serif;
    font-weight: 800;
    margin-bottom: -10px;
    letter-spacing: 2px;
}

            p{
                width: 39%;
                margin: 0 auto;
                line-height: 24px;
            }
            .btn{
                padding: 15px 40px;
                background: transparent;
                color: white;
                font-size: 19px;
                cursor: pointer;
                border-radius: 50px;
                outline: none;
                border: 2px solid white;
                font-family: 'Poppins', sans-serif;
                transition: all 0.5s ease-in-out;
            }
 
            
            .btn:hover{
                background: white;
                color: black;
            }
            
        </style>
    </head>
    <body>

        <div id="momoland">
            <div class="wrapper">
               <br><br><br>
                 
         
                <div id="carbon-block"></div>
<div> 
 </div>
</div>
 </div>

     

        <script src="daisy.js" defer></script>
      
        <script type="text/javascript">

  document.addEventListener('DOMContentLoaded', function () {
  daisyjs(document.getElementById('momoland'), {
    dotColor: '#fff',
    lineColor: '#ddd'
  });
}, false);


</script> 
    </body>
</html>

daisy.js

  1. ;(function(window, document) {
  2. "use strict";
  3. var pluginName = 'daisyjs';
  4. // http://youmightnotneedjquery.com/#deep_extend
  5. function extend(out) {
  6. out = out || {};
  7. for (var i = 1; i < arguments.length; i++) {
  8. var obj = arguments[i];
  9. if (!obj) continue;
  10. for (var key in obj) {
  11. if (obj.hasOwnProperty(key)) {
  12. if (typeof obj[key] === 'object')
  13. deepExtend(out[key], obj[key]);
  14. else
  15. out[key] = obj[key];
  16. }
  17. }
  18. }
  19. return out;
  20. }
  21. var $ = window.jQuery;
  22. function Plugin(element, options) {
  23. var canvasSupport = !!document.createElement('canvas').getContext;
  24. var canvas;
  25. var ctx;
  26. var particles = [];
  27. var raf;
  28. var mouseX = 0;
  29. var mouseY = 0;
  30. var winW;
  31. var winH;
  32. var desktop = !navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|BB10|mobi|tablet|opera mini|nexus 7)/i);
  33. var orientationSupport = !!window.DeviceOrientationEvent;
  34. var tiltX = 0;
  35. var pointerX;
  36. var pointerY;
  37. var tiltY = 0;
  38. var paused = false;
  39. options = extend({}, window[pluginName].defaults, options);
  40. /**
  41. * Init
  42. */
  43. function init() {
  44. if (!canvasSupport) { return; }
  45. // create canvas
  46. canvas = document.createElement('canvas');
  47. canvas.className = 'pg-canvas';
  48. canvas.style.display = 'block';
  49. element.insertBefore(canvas, element.firstChild);
  50. ctx = canvas.getContext('2d');
  51. styleCanvas();
  52. // create particles
  53. var numParticles = Math.round((canvas.width * canvas.height) / options.density);
  54. for (var i = 0; i < numParticles; i++) {
  55. var p = new Particle();
  56. p.setStackPos(i);
  57. particles.push(p);
  58. }
  59. window.addEventListener('resize', function() {
  60. resizeHandler();
  61. }, false);
  62. document.addEventListener('mousemove', function(e) {
  63. mouseX = e.pageX;
  64. mouseY = e.pageY;
  65. }, false);
  66. if (orientationSupport && !desktop) {
  67. window.addEventListener('deviceorientation', function () {
  68. // contrain tilt range to [-30,30]
  69. tiltY = Math.min(Math.max(-event.beta, -30), 30);
  70. tiltX = Math.min(Math.max(-event.gamma, -30), 30);
  71. }, true);
  72. }
  73. draw();
  74. hook('onInit');
  75. }
  76. /**
  77. * Style the canvas
  78. */
  79. function styleCanvas() {
  80. canvas.width = element.offsetWidth;
  81. canvas.height = element.offsetHeight;
  82. ctx.fillStyle = options.dotColor;
  83. ctx.strokeStyle = options.lineColor;
  84. ctx.lineWidth = options.lineWidth;
  85. }
  86. /**
  87. * Draw particles
  88. */
  89. function draw() {
  90. if (!canvasSupport) { return; }
  91. winW = window.innerWidth;
  92. winH = window.innerHeight;
  93. // wipe canvas
  94. ctx.clearRect(0, 0, canvas.width, canvas.height);
  95. // update particle positions
  96. for (var i = 0; i < particles.length; i++) {
  97. particles[i].updatePosition();
  98. }
  99. // draw particles
  100. for (i = 0; i < particles.length; i++) {
  101. particles[i].draw();
  102. }
  103. // call this function next time screen is redrawn
  104. if (!paused) {
  105. raf = requestAnimationFrame(draw);
  106. }
  107. }
  108. /**
  109. * Add/remove particles.
  110. */
  111. function resizeHandler() {
  112. // resize the canvas
  113. styleCanvas();
  114. var elWidth = element.offsetWidth;
  115. var elHeight = element.offsetHeight;
  116. // remove particles that are outside the canvas
  117. for (var i = particles.length - 1; i >= 0; i--) {
  118. if (particles[i].position.x > elWidth || particles[i].position.y > elHeight) {
  119. particles.splice(i, 1);
  120. }
  121. }
  122. // adjust particle density
  123. var numParticles = Math.round((canvas.width * canvas.height) / options.density);
  124. if (numParticles > particles.length) {
  125. while (numParticles > particles.length) {
  126. var p = new Particle();
  127. particles.push(p);
  128. }
  129. } else if (numParticles < particles.length) {
  130. particles.splice(numParticles);
  131. }
  132. // re-index particles
  133. for (i = particles.length - 1; i >= 0; i--) {
  134. particles[i].setStackPos(i);
  135. }
  136. }
  137. /**
  138. * Pause particle system
  139. */
  140. function pause() {
  141. paused = true;
  142. }
  143. /**
  144. * Start particle system
  145. */
  146. function start() {
  147. paused = false;
  148. draw();
  149. }
  150. /**
  151. * Particle
  152. */
  153. function Particle() {
  154. this.stackPos = this.stackPos;
  155. this.active = true;
  156. this.layer = Math.ceil(Math.random() * 3);
  157. this.parallaxOffsetX = 0;
  158. this.parallaxOffsetY = 0;
  159. // initial particle position
  160. this.position = {
  161. x: Math.ceil(Math.random() * canvas.width),
  162. y: Math.ceil(Math.random() * canvas.height)
  163. };
  164. // random particle speed, within min and max values
  165. this.speed = {};
  166. switch (options.directionX) {
  167. case 'left':
  168. this.speed.x = +(-options.maxSpeedX + (Math.random() * options.maxSpeedX) - options.minSpeedX).toFixed(2);
  169. break;
  170. case 'right':
  171. this.speed.x = +((Math.random() * options.maxSpeedX) + options.minSpeedX).toFixed(2);
  172. break;
  173. default:
  174. this.speed.x = +((-options.maxSpeedX / 2) + (Math.random() * options.maxSpeedX)).toFixed(2);
  175. this.speed.x += this.speed.x > 0 ? options.minSpeedX : -options.minSpeedX;
  176. break;
  177. }
  178. switch (options.directionY) {
  179. case 'up':
  180. this.speed.y = +(-options.maxSpeedY + (Math.random() * options.maxSpeedY) - options.minSpeedY).toFixed(2);
  181. break;
  182. case 'down':
  183. this.speed.y = +((Math.random() * options.maxSpeedY) + options.minSpeedY).toFixed(2);
  184. break;
  185. default:
  186. this.speed.y = +((-options.maxSpeedY / 2) + (Math.random() * options.maxSpeedY)).toFixed(2);
  187. this.speed.x += this.speed.y > 0 ? options.minSpeedY : -options.minSpeedY;
  188. break;
  189. }
  190. }
  191. /**
  192. * Draw particle
  193. */
  194. Particle.prototype.draw = function() {
  195. // draw circle
  196. ctx.beginPath();
  197. ctx.arc(this.position.x + this.parallaxOffsetX, this.position.y + this.parallaxOffsetY, options.particleRadius / 2, 0, Math.PI * 2, true);
  198. ctx.closePath();
  199. ctx.fill();
  200. // draw lines
  201. ctx.beginPath();
  202. // iterate over all particles which are higher in the stack than this one
  203. for (var i = particles.length - 1; i > this.stackPos; i--) {
  204. var p2 = particles[i];
  205. // pythagorus theorum to get distance between two points
  206. var a = this.position.x - p2.position.x;
  207. var b = this.position.y - p2.position.y;
  208. var dist = Math.sqrt((a * a) + (b * b)).toFixed(2);
  209. // if the two particles are in proximity, join them
  210. if (dist < options.proximity) {
  211. ctx.moveTo(this.position.x + this.parallaxOffsetX, this.position.y + this.parallaxOffsetY);
  212. if (options.curvedLines) {
  213. ctx.quadraticCurveTo(Math.max(p2.position.x, p2.position.x), Math.min(p2.position.y, p2.position.y), p2.position.x + p2.parallaxOffsetX, p2.position.y + p2.parallaxOffsetY);
  214. } else {
  215. ctx.lineTo(p2.position.x + p2.parallaxOffsetX, p2.position.y + p2.parallaxOffsetY);
  216. }
  217. }
  218. }
  219. ctx.stroke();
  220. ctx.closePath();
  221. };
  222. /**
  223. * Update particle position
  224. */
  225. Particle.prototype.updatePosition = function() {
  226. if (options.parallax) {
  227. if (orientationSupport && !desktop) {
  228. // map tiltX range [-30,30] to range [0,winW]
  229. var ratioX = (winW - 0) / (30 - (-30));
  230. pointerX = (tiltX - (-30)) * ratioX + 0;
  231. // map tiltY range [-30,30] to range [0,winH]
  232. var ratioY = (winH - 0) / (30 - (-30));
  233. pointerY = (tiltY - (-30)) * ratioY + 0;
  234. } else {
  235. pointerX = mouseX;
  236. pointerY = mouseY;
  237. }
  238. // calculate parallax offsets
  239. this.parallaxTargX = (pointerX - (winW / 2)) / (options.parallaxMultiplier * this.layer);
  240. this.parallaxOffsetX += (this.parallaxTargX - this.parallaxOffsetX) / 10; // easing equation
  241. this.parallaxTargY = (pointerY - (winH / 2)) / (options.parallaxMultiplier * this.layer);
  242. this.parallaxOffsetY += (this.parallaxTargY - this.parallaxOffsetY) / 10; // easing equation
  243. }
  244. var elWidth = element.offsetWidth;
  245. var elHeight = element.offsetHeight;
  246. switch (options.directionX) {
  247. case 'left':
  248. if (this.position.x + this.speed.x + this.parallaxOffsetX < 0) {
  249. this.position.x = elWidth - this.parallaxOffsetX;
  250. }
  251. break;
  252. case 'right':
  253. if (this.position.x + this.speed.x + this.parallaxOffsetX > elWidth) {
  254. this.position.x = 0 - this.parallaxOffsetX;
  255. }
  256. break;
  257. default:
  258. // if particle has reached edge of canvas, reverse its direction
  259. if (this.position.x + this.speed.x + this.parallaxOffsetX > elWidth || this.position.x + this.speed.x + this.parallaxOffsetX < 0) {
  260. this.speed.x = -this.speed.x;
  261. }
  262. break;
  263. }
  264. switch (options.directionY) {
  265. case 'up':
  266. if (this.position.y + this.speed.y + this.parallaxOffsetY < 0) {
  267. this.position.y = elHeight - this.parallaxOffsetY;
  268. }
  269. break;
  270. case 'down':
  271. if (this.position.y + this.speed.y + this.parallaxOffsetY > elHeight) {
  272. this.position.y = 0 - this.parallaxOffsetY;
  273. }
  274. break;
  275. default:
  276. // if particle has reached edge of canvas, reverse its direction
  277. if (this.position.y + this.speed.y + this.parallaxOffsetY > elHeight || this.position.y + this.speed.y + this.parallaxOffsetY < 0) {
  278. this.speed.y = -this.speed.y;
  279. }
  280. break;
  281. }
  282. // move particle
  283. this.position.x += this.speed.x;
  284. this.position.y += this.speed.y;
  285. };
  286. /**
  287. * Setter: particle stacking position
  288. */
  289. Particle.prototype.setStackPos = function(i) {
  290. this.stackPos = i;
  291. };
  292. function option (key, val) {
  293. if (val) {
  294. options[key] = val;
  295. } else {
  296. return options[key];
  297. }
  298. }
  299. function destroy() {
  300. console.log('destroy');
  301. canvas.parentNode.removeChild(canvas);
  302. hook('onDestroy');
  303. if ($) {
  304. $(element).removeData('plugin_' + pluginName);
  305. }
  306. }
  307. function hook(hookName) {
  308. if (options[hookName] !== undefined) {
  309. options[hookName].call(element);
  310. }
  311. }
  312. init();
  313. return {
  314. option: option,
  315. destroy: destroy,
  316. start: start,
  317. pause: pause
  318. };
  319. }
  320. window[pluginName] = function(elem, options) {
  321. return new Plugin(elem, options);
  322. };
  323. window[pluginName].defaults = {
  324. minSpeedX: 0.1,
  325. maxSpeedX: 0.7,
  326. minSpeedY: 0.1,
  327. maxSpeedY: 0.7,
  328. directionX: 'center', // 'center', 'left' or 'right'. 'center' = dots bounce off edges
  329. directionY: 'center', // 'center', 'up' or 'down'. 'center' = dots bounce off edges
  330. density: 10000, // how many particles will be generated: one particle every n pixels
  331. dotColor: '#666666',
  332. lineColor: '#666666',
  333. particleRadius: 7, // dot size
  334. lineWidth: 1,
  335. curvedLines: false,
  336. proximity: 100, // how close two dots need to be before they join
  337. parallax: true,
  338. parallaxMultiplier: 5, // the lower the number, the more extreme the parallax effect
  339. onInit: function() {},
  340. onDestroy: function() {}
  341. };
  342. // nothing wrong with hooking into jQuery if it's there...
  343. if ($) {
  344. $.fn[pluginName] = function(options) {
  345. if (typeof arguments[0] === 'string') {
  346. var methodName = arguments[0];
  347. var args = Array.prototype.slice.call(arguments, 1);
  348. var returnVal;
  349. this.each(function() {
  350. if ($.data(this, 'plugin_' + pluginName) && typeof $.data(this, 'plugin_' + pluginName)[methodName] === 'function') {
  351. returnVal = $.data(this, 'plugin_' + pluginName)[methodName].apply(this, args);
  352. }
  353. });
  354. if (returnVal !== undefined){
  355. return returnVal;
  356. } else {
  357. return this;
  358. }
  359. } else if (typeof options === "object" || !options) {
  360. return this.each(function() {
  361. if (!$.data(this, 'plugin_' + pluginName)) {
  362. $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
  363. }
  364. });
  365. }
  366. };
  367. }
  368. })(window, document);
  369. /**
  370. * requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
  371. * @see: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  372. * @see: http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  373. * @license: MIT license
  374. */
  375. (function() {
  376. var lastTime = 0;
  377. var vendors = ['ms', 'moz', 'webkit', 'o'];
  378. for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
  379. window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
  380. window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
  381. }
  382. if (!window.requestAnimationFrame)
  383. window.requestAnimationFrame = function(callback, element) {
  384. var currTime = new Date().getTime();
  385. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  386. var id = window.setTimeout(function() { callback(currTime + timeToCall); },
  387. timeToCall);
  388. lastTime = currTime + timeToCall;
  389. return id;
  390. };
  391. if (!window.cancelAnimationFrame)
  392. window.cancelAnimationFrame = function(id) {
  393. clearTimeout(id);
  394. };
  395. }());
;(function(window, document) {
  "use strict";
  var pluginName = 'daisyjs';

  // http://youmightnotneedjquery.com/#deep_extend
  function extend(out) {
    out = out || {};
    for (var i = 1; i < arguments.length; i++) {
      var obj = arguments[i];
      if (!obj) continue;
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (typeof obj[key] === 'object')
            deepExtend(out[key], obj[key]);
          else
            out[key] = obj[key];
        }
      }
    }
    return out;
  }

  var $ = window.jQuery;

  function Plugin(element, options) {
    var canvasSupport = !!document.createElement('canvas').getContext;
    var canvas;
    var ctx;
    var particles = [];
    var raf;
    var mouseX = 0;
    var mouseY = 0;
    var winW;
    var winH;
    var desktop = !navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|BB10|mobi|tablet|opera mini|nexus 7)/i);
    var orientationSupport = !!window.DeviceOrientationEvent;
    var tiltX = 0;
    var pointerX;
    var pointerY;
    var tiltY = 0;
    var paused = false;

    options = extend({}, window[pluginName].defaults, options);

    /**
     * Init
     */
    function init() {
      if (!canvasSupport) { return; }

      // create canvas
      canvas = document.createElement('canvas');
      canvas.className = 'pg-canvas';
      canvas.style.display = 'block';
      element.insertBefore(canvas, element.firstChild);
      ctx = canvas.getContext('2d');
      styleCanvas();

      // create particles
      var numParticles = Math.round((canvas.width * canvas.height) / options.density);
      for (var i = 0; i < numParticles; i++) {
        var p = new Particle();
        p.setStackPos(i);
        particles.push(p);
      }

      window.addEventListener('resize', function() {
        resizeHandler();
      }, false);

      document.addEventListener('mousemove', function(e) {
        mouseX = e.pageX;
        mouseY = e.pageY;
      }, false);

      if (orientationSupport && !desktop) {
        window.addEventListener('deviceorientation', function () {
          // contrain tilt range to [-30,30]
          tiltY = Math.min(Math.max(-event.beta, -30), 30);
          tiltX = Math.min(Math.max(-event.gamma, -30), 30);
        }, true);
      }

      draw();
      hook('onInit');
    }

    /**
     * Style the canvas
     */
    function styleCanvas() {
      canvas.width = element.offsetWidth;
      canvas.height = element.offsetHeight;
      ctx.fillStyle = options.dotColor;
      ctx.strokeStyle = options.lineColor;
      ctx.lineWidth = options.lineWidth;
    }

    /**
     * Draw particles
     */
    function draw() {
      if (!canvasSupport) { return; }

      winW = window.innerWidth;
      winH = window.innerHeight;

      // wipe canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // update particle positions
      for (var i = 0; i < particles.length; i++) {
        particles[i].updatePosition();
      }
      // draw particles
      for (i = 0; i < particles.length; i++) {
        particles[i].draw();
      }

      // call this function next time screen is redrawn
      if (!paused) {
        raf = requestAnimationFrame(draw);
      }
    }

    /**
     * Add/remove particles.
     */
    function resizeHandler() {
      // resize the canvas
      styleCanvas();

      var elWidth = element.offsetWidth;
      var elHeight = element.offsetHeight;

      // remove particles that are outside the canvas
      for (var i = particles.length - 1; i >= 0; i--) {
        if (particles[i].position.x > elWidth || particles[i].position.y > elHeight) {
          particles.splice(i, 1);
        }
      }

      // adjust particle density
      var numParticles = Math.round((canvas.width * canvas.height) / options.density);
      if (numParticles > particles.length) {
        while (numParticles > particles.length) {
          var p = new Particle();
          particles.push(p);
        }
      } else if (numParticles < particles.length) {
        particles.splice(numParticles);
      }

      // re-index particles
      for (i = particles.length - 1; i >= 0; i--) {
        particles[i].setStackPos(i);
      }
    }

    /**
     * Pause particle system
     */
    function pause() {
      paused = true;
    }

    /**
     * Start particle system
     */
    function start() {
      paused = false;
      draw();
    }

    /**
     * Particle
     */
    
    function Particle() {
      this.stackPos = this.stackPos; 
      this.active = true;
      this.layer = Math.ceil(Math.random() * 3);
      this.parallaxOffsetX = 0;
      this.parallaxOffsetY = 0;
      // initial particle position
      this.position = {
        x: Math.ceil(Math.random() * canvas.width),
        y: Math.ceil(Math.random() * canvas.height)
      };
      // random particle speed, within min and max values
      this.speed = {};
      switch (options.directionX) {
        case 'left':
          this.speed.x = +(-options.maxSpeedX + (Math.random() * options.maxSpeedX) - options.minSpeedX).toFixed(2);
          break;
        case 'right':
          this.speed.x = +((Math.random() * options.maxSpeedX) + options.minSpeedX).toFixed(2);
          break;
        default:
          this.speed.x = +((-options.maxSpeedX / 2) + (Math.random() * options.maxSpeedX)).toFixed(2);
          this.speed.x += this.speed.x > 0 ? options.minSpeedX : -options.minSpeedX;
          break;
      }
      switch (options.directionY) {
        case 'up':
          this.speed.y = +(-options.maxSpeedY + (Math.random() * options.maxSpeedY) - options.minSpeedY).toFixed(2);
          break;
        case 'down':
          this.speed.y = +((Math.random() * options.maxSpeedY) + options.minSpeedY).toFixed(2);
          break;
        default:
          this.speed.y = +((-options.maxSpeedY / 2) + (Math.random() * options.maxSpeedY)).toFixed(2);
          this.speed.x += this.speed.y > 0 ? options.minSpeedY : -options.minSpeedY;
          break;
      }
    }

    /**
     * Draw particle
     */
    Particle.prototype.draw = function() {
      // draw circle
      ctx.beginPath();
      ctx.arc(this.position.x + this.parallaxOffsetX, this.position.y + this.parallaxOffsetY, options.particleRadius / 2, 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.fill();

      // draw lines
      ctx.beginPath();
      // iterate over all particles which are higher in the stack than this one
      for (var i = particles.length - 1; i > this.stackPos; i--) {
        var p2 = particles[i];

        // pythagorus theorum to get distance between two points
        var a = this.position.x - p2.position.x;
        var b = this.position.y - p2.position.y;
        var dist = Math.sqrt((a * a) + (b * b)).toFixed(2);

        // if the two particles are in proximity, join them
        if (dist < options.proximity) {
          ctx.moveTo(this.position.x + this.parallaxOffsetX, this.position.y + this.parallaxOffsetY);
          if (options.curvedLines) {
            ctx.quadraticCurveTo(Math.max(p2.position.x, p2.position.x), Math.min(p2.position.y, p2.position.y), p2.position.x + p2.parallaxOffsetX, p2.position.y + p2.parallaxOffsetY);
          } else {
            ctx.lineTo(p2.position.x + p2.parallaxOffsetX, p2.position.y + p2.parallaxOffsetY);
          }
        }
      }
      ctx.stroke();
      ctx.closePath();
    };

    /**
     * Update particle position
     */
    Particle.prototype.updatePosition = function() {
      if (options.parallax) {
        if (orientationSupport && !desktop) {
          // map tiltX range [-30,30] to range [0,winW]
          var ratioX = (winW - 0) / (30 - (-30));
          pointerX = (tiltX - (-30)) * ratioX + 0;
          // map tiltY range [-30,30] to range [0,winH]
          var ratioY = (winH - 0) / (30 - (-30));
          pointerY = (tiltY - (-30)) * ratioY + 0;
        } else {
          pointerX = mouseX;
          pointerY = mouseY;
        }
        // calculate parallax offsets
        this.parallaxTargX = (pointerX - (winW / 2)) / (options.parallaxMultiplier * this.layer);
        this.parallaxOffsetX += (this.parallaxTargX - this.parallaxOffsetX) / 10; // easing equation
        this.parallaxTargY = (pointerY - (winH / 2)) / (options.parallaxMultiplier * this.layer);
        this.parallaxOffsetY += (this.parallaxTargY - this.parallaxOffsetY) / 10; // easing equation
      }

      var elWidth = element.offsetWidth;
      var elHeight = element.offsetHeight;

      switch (options.directionX) {
        case 'left':
          if (this.position.x + this.speed.x + this.parallaxOffsetX < 0) {
            this.position.x = elWidth - this.parallaxOffsetX;
          }
          break;
        case 'right':
          if (this.position.x + this.speed.x + this.parallaxOffsetX > elWidth) {
            this.position.x = 0 - this.parallaxOffsetX;
          }
          break;
        default:
          // if particle has reached edge of canvas, reverse its direction
          if (this.position.x + this.speed.x + this.parallaxOffsetX > elWidth || this.position.x + this.speed.x + this.parallaxOffsetX < 0) {
            this.speed.x = -this.speed.x;
          }
          break;
      }

      switch (options.directionY) {
        case 'up':
          if (this.position.y + this.speed.y + this.parallaxOffsetY < 0) {
            this.position.y = elHeight - this.parallaxOffsetY;
          }
          break;
        case 'down':
          if (this.position.y + this.speed.y + this.parallaxOffsetY > elHeight) {
            this.position.y = 0 - this.parallaxOffsetY;
          }
          break;
        default:
          // if particle has reached edge of canvas, reverse its direction
          if (this.position.y + this.speed.y + this.parallaxOffsetY > elHeight || this.position.y + this.speed.y + this.parallaxOffsetY < 0) {
            this.speed.y = -this.speed.y;
          }
          break;
      }

      // move particle
      this.position.x += this.speed.x;
      this.position.y += this.speed.y;
    };

    /**
     * Setter: particle stacking position
     */
    Particle.prototype.setStackPos = function(i) {
      this.stackPos = i;
    };

    function option (key, val) {
      if (val) {
        options[key] = val;
      } else {
        return options[key];
      }
    }

    function destroy() {
      console.log('destroy');
      canvas.parentNode.removeChild(canvas);
      hook('onDestroy');
      if ($) {
        $(element).removeData('plugin_' + pluginName);
      }
    }

    function hook(hookName) {
      if (options[hookName] !== undefined) {
        options[hookName].call(element);
      }
    }

    init();

    return {
      option: option,
      destroy: destroy,
      start: start,
      pause: pause
    };
  }

  window[pluginName] = function(elem, options) {
    return new Plugin(elem, options);
  };

  window[pluginName].defaults = {
    minSpeedX: 0.1,
    maxSpeedX: 0.7,
    minSpeedY: 0.1,
    maxSpeedY: 0.7,
    directionX: 'center', // 'center', 'left' or 'right'. 'center' = dots bounce off edges
    directionY: 'center', // 'center', 'up' or 'down'. 'center' = dots bounce off edges
    density: 10000, // how many particles will be generated: one particle every n pixels
    dotColor: '#666666',
    lineColor: '#666666',
    particleRadius: 7, // dot size
    lineWidth: 1,
    curvedLines: false,
    proximity: 100, // how close two dots need to be before they join
    parallax: true,
    parallaxMultiplier: 5, // the lower the number, the more extreme the parallax effect
    onInit: function() {},
    onDestroy: function() {}
  };

  // nothing wrong with hooking into jQuery if it's there...
  if ($) {
    $.fn[pluginName] = function(options) {
      if (typeof arguments[0] === 'string') {
        var methodName = arguments[0];
        var args = Array.prototype.slice.call(arguments, 1);
        var returnVal;
        this.each(function() {
          if ($.data(this, 'plugin_' + pluginName) && typeof $.data(this, 'plugin_' + pluginName)[methodName] === 'function') {
            returnVal = $.data(this, 'plugin_' + pluginName)[methodName].apply(this, args);
          }
        });
        if (returnVal !== undefined){
          return returnVal;
        } else {
          return this;
        }
      } else if (typeof options === "object" || !options) {
        return this.each(function() {
          if (!$.data(this, 'plugin_' + pluginName)) {
            $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
          }
        });
      }
    };
  }

})(window, document);

/**
 * requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
 * @see: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
 * @see: http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
 * @license: MIT license
 */
(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
      window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
      window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
      window.requestAnimationFrame = function(callback, element) {
        var currTime = new Date().getTime();
        var timeToCall = Math.max(0, 16 - (currTime - lastTime));
        var id = window.setTimeout(function() { callback(currTime + timeToCall); },
          timeToCall);
        lastTime = currTime + timeToCall;
        return id;
      };

    if (!window.cancelAnimationFrame)
      window.cancelAnimationFrame = function(id) {
        clearTimeout(id);
      };
}());

 在线演示


让链接同时具备两种打开方式

获取源码: 如何在HTML CSS JS制作网页中鼠标拖拽粒子效果动画背景cid1146
下载数:218人次, 文件大小: 783.3 KB, 上传日期: 2021年-2 月-21日

公众号回复:gcode  获取解压密码

qrcode_for_gh_6ea2c28a1709_258 (1)

3,981 人查阅

类似文章