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>Document</title>
    7. <style>
    8. body {
    9. margin: 0;
    10. overflow: hidden;
    11. }
    12. canvas {
    13. background: #000;
    14. }
    15. </style>
    16. </head>
    17. <body>
    18. <canvas id="canvas"></canvas>
    19. <script>
    20. /**@type{HTMLCanvasElement}*/
    21. const canvas = document.getElementById('canvas');
    22. canvas.width = window.innerWidth;
    23. canvas.height = window.innerHeight;
    24. const ctx = canvas.getContext('2d')
    25. const random = Symbol('random')
    26. const arcArr =[]
    27. ctx.save()
    28. class Arc {
    29. constructor(x, y) {
    30. /**
    31. * x轴位置
    32. * y轴位置
    33. * x轴方向移速
    34. * y轴方向移速
    35. * 透明度
    36. * 透明度衰减值
    37. * 随机圆的半径
    38. * 随机圆得颜色
    39. */
    40. this.x = x;
    41. this.y = y;
    42. this.speeedX = (Math.random() - 0.5) * 3;
    43. this.speeedY = (Math.random() - 0.5) * 3;
    44. this.opacity = 1 ;
    45. this.opacitySpeed = 0.96;
    46. this.r = this[random](10,18);
    47. this.color = 'rgb(' + this[random](0, 255) + ',' + this[random](0, 255) + ',' + this[random](0, 255) + ')';
    48. }
    49. /**
    50. * 绘制圆
    51. */
    52. rendom(){
    53. ctx.beginPath();
    54. ctx.arc(this.x,this.y,this.r,0,Math.PI*2)
    55. ctx.fillStyle = this.color;
    56. ctx.globalAlpha = this.opacity;
    57. // 设置多个圆形重叠时的样式,
    58. ctx.globalCompositeOperation = 'lighter'
    59. ctx.fill()
    60. this.moveArc()
    61. }
    62. /**
    63. * 获取两个数之间的随机数
    64. */
    65. [random](min,max){
    66. return Math.round(Math.random() * (max - min) + min )
    67. }
    68. /**
    69. * 修改器坐标使圆移动
    70. */
    71. moveArc(){
    72. this.x += this.speeedX;
    73. this.y += this.speeedY;
    74. this.opacity *= this.opacitySpeed;
    75. }
    76. }
    77. canvas.onmousemove = function(e){
    78. arcArr.push(new Arc(e.clientX,e.clientY))
    79. }
    80. function render(){
    81. // 清空画布
    82. ctx.clearRect(0,0,canvas.width,canvas.height)
    83. // 让圆移动,和圆何时彻底消失
    84. for(let i = 0 ; i < arcArr.length; i++){
    85. arcArr[i].rendom()
    86. if(arcArr[i].opacity <0.05){
    87. arcArr.splice(i,1)
    88. }
    89. }
    90. // 在浏览器下次重绘之前调用render函数
    91. requestAnimationFrame(render);
    92. }
    93. render()
    94. </script>
    95. </body>
    96. </html>