当前位置:   article > 正文

JS特效第132弹:canvas圆点分散光标跟随动画特效代码

JS特效第132弹:canvas圆点分散光标跟随动画特效代码

        基于canvas制作跟随鼠标移动的彩色圆点粒子分散动画特效 ,先来看看效果:

        一部分关键的代码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title></title>
  7. <style>
  8. * {
  9. margin: 0;
  10. padding: 0;
  11. }
  12. body {
  13. overflow: hidden;
  14. }
  15. canvas {
  16. background-color: black;
  17. transition: all .2s;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <canvas id="canvas"></canvas>
  23. <script circleWidth='10' id="cvs">
  24. /** @type {HTMLCanvasElement} */
  25. // 初始化画板
  26. const canvas = document.querySelector('#canvas');
  27. canvas.width = window.innerWidth;
  28. canvas.height = window.innerHeight;
  29. // 初始化画笔
  30. const cvs = canvas.getContext('2d');
  31. let CircleArr = [];
  32. // 实例化对象
  33. canvas.addEventListener('mousemove', function (ev) {
  34. let cir = new Circle(ev.pageX, ev.pageY);
  35. CircleArr.push(cir);
  36. })
  37. canvas.addEventListener('touchmove', function (ev) {
  38. let cir = new Circle(ev.touches[0].clientX, ev.touches[0].clientY);
  39. CircleArr.push(cir);
  40. })
  41. /**
  42. * 主要参数位置
  43. */
  44. function Circle(X, Y) {
  45. this.X = Math.floor(X);
  46. this.Y = Math.floor(Y);
  47. this.speedX = Math.floor((Math.random() - 0.5) * 4);
  48. this.speedY = Math.floor((Math.random() - 0.5) * 4);
  49. this.A = 1;
  50. this.R = +document.getElementById('cvs').getAttribute('circleWidth') || 20;
  51. }
  52. Circle.prototype = {
  53. // 画圆
  54. draw() {
  55. cvs.beginPath();
  56. cvs.fillStyle =
  57. `rgb(${Math.floor(Math.random()*255)},${Math.floor(Math.random()*255)},${Math.floor(Math.random()*255)})`;
  58. cvs.globalCompositeOperation = "lighter";
  59. cvs.globalAlpha = this.A;
  60. cvs.arc(this.X, this.Y, this.R, 0, Math.PI * 2);
  61. cvs.fill();
  62. this.upDate();
  63. },
  64. // 更新圆的状态
  65. upDate() {
  66. this.X += this.speedX;
  67. this.Y += this.speedY;
  68. this.A *= 0.98;
  69. }
  70. }
  71. // 清除重画
  72. function render() {
  73. cvs.clearRect(0, 0, canvas.width, canvas.height);
  74. CircleArr.forEach(function (ele, i) {
  75. ele.draw();
  76. // 删除已经执行完的圆优化性能
  77. if (ele.A < 0.03) {
  78. CircleArr.splice(i, 1)
  79. }
  80. });
  81. //关键帧的刷新
  82. requestAnimationFrame(render);
  83. }
  84. render()
  85. </script>
  86. </body>
  87. </html>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/90968
推荐阅读