ui.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // 中间背景雨
  2. export function rainBg(className, bgClassName) {
  3. var c = document.querySelector(`.${className}`);
  4. if (!c) return
  5. var ctx = c.getContext('2d'); //获取canvas上下文
  6. var w = (c.width = document.querySelector(`.${bgClassName}`).clientWidth);
  7. var h = (c.height = document.querySelector(`.${bgClassName}`).clientHeight);
  8. //设置canvas宽、高
  9. function random(min, max) {
  10. return Math.random() * (max - min) + min;
  11. }
  12. function RainDrop() { }
  13. //雨滴对象 这是绘制雨滴动画的关键
  14. RainDrop.prototype = {
  15. init: function () {
  16. this.x = random(0, w); //雨滴的位置x
  17. this.y = h; //雨滴的位置y
  18. this.color = 'hsl(180, 100%, 50%)'; //雨滴颜色 长方形的填充色
  19. this.vy = random(4, 5); //雨滴下落速度
  20. this.hit = 0; //下落的最大值
  21. this.size = 2; //长方形宽度
  22. },
  23. draw: function () {
  24. if (this.y > this.hit) {
  25. var linearGradient = ctx.createLinearGradient(this.x, this.y, this.x, this.y + this.size * 30);
  26. // 设置起始颜色
  27. linearGradient.addColorStop(0, '#14789c');
  28. // 设置终止颜色
  29. linearGradient.addColorStop(1, '#090723');
  30. // 设置填充样式
  31. ctx.fillStyle = linearGradient;
  32. ctx.fillRect(this.x, this.y, this.size, this.size * 50); //绘制长方形,通过多次叠加长方形,形成雨滴下落效果
  33. }
  34. this.update(); //更新位置
  35. },
  36. update: function () {
  37. if (this.y > this.hit) {
  38. this.y -= this.vy; //未达到底部,增加雨滴y坐标
  39. } else {
  40. this.init();
  41. }
  42. },
  43. };
  44. function resize() {
  45. w = c.width = window.innerWidth;
  46. h = c.height = window.innerHeight;
  47. }
  48. //初始化一个雨滴
  49. var rs = [];
  50. for (var i = 0; i < 10; i++) {
  51. setTimeout(function () {
  52. var r = new RainDrop();
  53. r.init();
  54. rs.push(r);
  55. }, i * 300);
  56. }
  57. function anim() {
  58. ctx.clearRect(0, 0, w, h); //填充背景色,注意不要用clearRect,否则会清空前面的雨滴,导致不能产生叠加的效果
  59. for (var i = 0; i < rs.length; i++) {
  60. rs[i].draw(); //绘制雨滴
  61. }
  62. requestAnimationFrame(anim); //控制动画帧
  63. }
  64. window.addEventListener('resize', resize);
  65. //启动动画
  66. anim();
  67. }
  68. // 获取图片资源路径
  69. export const getAssetURL = (image) => {
  70. // 参数一: 相对路径
  71. // 参数二: 当前路径的URL
  72. return new URL(`../assets/images/${image}`, import.meta.url).href
  73. }