Newer
Older
KaiFengPC / src / views / sponeScreen / projectHM / canvasRainSS.vue
@zhangdeliang zhangdeliang on 10 Sep 2 KB update
  1. <template>
  2. <!-- 降雨效果canvas -->
  3. <div class="canvasRainPage">
  4. <canvas id="canvasRainSS"></canvas>
  5. </div>
  6. </template>
  7.  
  8. <script setup>
  9. const { proxy } = getCurrentInstance();
  10. const props = defineProps({
  11. width: { type: Number },
  12. height: { type: Number },
  13. });
  14. const timer = ref(null);
  15.  
  16. // 画笔
  17. const ctx = ref(null);
  18. // 画布的宽高
  19. let w = props.width;
  20. let h = props.height;
  21. // 存放雨滴的数组
  22. let arr = [];
  23. // 雨滴的数量
  24. const size = ref(200);
  25. // 雨滴的构造函数
  26. class Rain {
  27. x = random(w);
  28. y = random(h);
  29. ySpeed = random(2) + 8;
  30. show() {
  31. drawLine(this.x, this.y);
  32. }
  33. run() {
  34. if (this.y > h) {
  35. this.y = 0;
  36. this.x = random(w);
  37. }
  38. this.y = this.y + this.ySpeed;
  39. }
  40. }
  41. // 画线(雨滴)
  42. function drawLine(x1, y1) {
  43. ctx.value.beginPath();
  44. ctx.value.strokeStyle = 'rgba(35, 195, 255, 0.6)';
  45. ctx.value.moveTo(x1, y1);
  46. // 雨长度
  47. ctx.value.lineTo(x1, y1 + 20);
  48. ctx.value.stroke();
  49. }
  50. // 生成随机数
  51. function random(num) {
  52. return Math.random() * num;
  53. }
  54. // 开始
  55. function start() {
  56. for (let i = 0; i < size.value; i++) {
  57. let rain = new Rain();
  58. arr.push(rain);
  59. rain.show();
  60. }
  61. timer.value = setInterval(() => {
  62. ctx.value.clearRect(0, 0, w, h);
  63. for (let i = 0; i < size.value; i++) {
  64. arr[i].show();
  65. arr[i].run();
  66. }
  67. }, 30);
  68. }
  69. // 初始化
  70. function init(ctx1) {
  71. ctx.value = ctx1;
  72. start();
  73. }
  74.  
  75. // 清除画布
  76. function clearDraw() {
  77. ctx.value.clearRect(0, 0, w, h);
  78. }
  79.  
  80. // 初始化
  81. function initCanvas() {
  82. const canvas = document.querySelector('#canvasRainSS');
  83. ctx.value = canvas.getContext('2d');
  84. canvas.width = w;
  85. canvas.height = h;
  86. init(ctx.value);
  87. }
  88.  
  89. onMounted(() => {
  90. initCanvas();
  91. });
  92. onBeforeUnmount(() => {
  93. if (timer.value) clearInterval(timer.value);
  94. clearDraw();
  95. });
  96. </script>
  97.  
  98. <style lang="scss" scoped>
  99. .canvasRainPage {
  100. width: 100%;
  101. height: 100%;
  102. background: rgba(0, 59, 109, 0.2);
  103. position: absolute;
  104. left: 0px;
  105. top: 0px;
  106. z-index: 100;
  107. pointer-events: none;
  108. }
  109. </style>