• js实现红包雨功能(canvas,react,ts),包括图片不规则旋转、大小、转速、掉落速度控制、屏幕最大红包数量控制等功能


    介绍

    1. 本文功能由canvas实现红包雨功能(index.tsx
    2. 本文为react的ts版。如有其他版本需求可评论区
    3. 观赏地址,需过墙
    import React, { Component } from 'react';
    // import './index.css';
    import moneyx from '@/assets/images/RedEnvelopeRain/ball1.png';
    import money1 from '@/assets/images/RedEnvelopeRain/money1.webp';
    import money2 from '@/assets/images/pointCon/机器人.png';
    import money3 from '@/assets/images/pointCon/无人机.png';
    import {
      loadImage,
      positionX,
      randomRange,
    } from './utils';
    type minMax = [number, number];
    const config = {
      // speed value area
      speedLimit: [1, 4] as minMax,
      // display quantity
      density: [5, 15] as minMax,
      imgInfo: {
        // image width
        w: 50,
        // image height
        h: 50,
        // image rotate value area
        randomLimit: [0.5, 1] as minMax,
      },
      // image number max show
      numberMaxLimit: 200,
    };
    const { speedLimit, imgInfo, numberMaxLimit, density } = config;
    
    export default class CanvasCom extends Component {
      // ratio = null;
      ctx: any = null;
    
      wid = 0;
      hei = 0;
      packedArr: ReturnType<typeof this.createPack>[] = [];
      // display quantity
      density = {
        min: density[0],
        max: density[1],
      };
    
      clearTime: any = null;
      img: any = [];
      loadingImageArr = [money1, moneyx, money2, money3]
    
      componentDidMount() {
        this.loadingImg();
      }
      loadingImg() {
        Promise.all(this.loadingImageArr.map(v => loadImage(v))).then((res) => {
          this.img = res;
          this.wid = window.innerWidth;
          this.hei = window.innerHeight;
          this.initCanvas();
          this.start();
        });
      }
      getPixelRatio = (context: any) => {
        const backingStore =
          context.backingStorePixelRatio ||
          context.webkitBackingStorePixelRatio ||
          context.mozBackingStorePixelRatio ||
          context.msBackingStorePixelRatio ||
          context.oBackingStorePixelRatio ||
          context.backingStorePixelRatio ||
          1;
        return (window.devicePixelRatio || 1) / backingStore;
      };
      initCanvas() {
        const canvas: HTMLCanvasElement | any = document.getElementById('canvas');
        canvas.width = this.wid;
        canvas.height = this.hei;
        if (canvas.getContext) {
          // 判断是否有此方法,如果有才能进入
          this.ctx = canvas.getContext('2d');
          // this.ratio = this.getPixelRatio(this.ctx);
        }
      }
      createPack() {
        const imgRandom = randomRange(...imgInfo.randomLimit);
        return {
          x: positionX(),
          y: 0,
          img: this.img[Math.floor(randomRange(0, this.loadingImageArr.length ))],
          // rotate
          rotate: randomRange(-45, 45),
          direction: Math.random(),
          speed: randomRange(...speedLimit),
          // rotate speed
          round: 0,
          roundSpeed: randomRange(1, 2),
          imgInfo: {
            w: imgInfo.w * imgRandom,
            h: imgInfo.h * imgRandom,
          },
        };
      }
      pushPackArr = () => {
        const { max, min } = this.density;
        const random = Math.floor(Math.random() * (max - min) + min);
        this.packedArr.push(
          ...new Array(random).fill('').map(() => this.createPack())
        );
        this.clearTime = setTimeout(() => {
          if (this.packedArr.length > numberMaxLimit)
            return clearTimeout(this.clearTime);
          this.pushPackArr();
        }, 300);
      };
      drawPacked = () => {
        this.ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
        this.packedArr.forEach((item, index) => {
          const r = ((item.rotate + item.round) * Math.PI) / 180;
          const temp = item.y - item.x * Math.tan(r);
          const top = temp * Math.cos(r);
          const left = item.x / Math.cos(r) + temp * Math.sin(r);
          this.ctx.save();
          this.ctx.rotate(r);
          this.ctx.drawImage(
            item.img,
            left - item.imgInfo.w / 2,
            top - item.imgInfo.h / 2,
            item.imgInfo.w,
            item.imgInfo.h
          );
          this.ctx.restore();
          if (item.direction < 0.5) {
            item.round -= item.roundSpeed;
          } else {
            item.round += item.roundSpeed;
          }
          if (item.y + item?.speed <= window.innerHeight) {
            item.y = item.y + item?.speed || 0;
          } else {
            // init
            item.y = 0 + item?.speed || 0;
            item.x = positionX();
            Object.assign(item, this.createPack());
          }
        });
        window.requestAnimationFrame(this.drawPacked);
      };
    
      start = () => {
        this.pushPackArr();
        this.drawPacked();
      };
    
      render() {
        return (
          <div style={{ position: 'absolute', left: 0, top: 0, background: '#000' }}>
            <canvas id="canvas"></canvas>
          </div>
        );
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    1. utils/index.ts
    export const loadImage = (url: string) => {
      if (!window?.Image) return null;
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = url;
        img.onload = () => {
          resolve(img);
        };
        img.onerror = () => {
          reject(new Error('load image error!'));
        };
      });
    };
    export const positionX = () => Math.random() * window.innerWidth;
    export const randomRange = (start: number, end: number) => {
      const random = (end - start) * Math.random() + start;
      const number = 1;
      const arr = new Array(number).fill('').map((v, i) => random / (i + 1));
      return arr[Math.floor(Math.random() * number)];
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    效果图

    在这里插入图片描述
    在这里插入图片描述

  • 相关阅读:
    JAVA二叉搜索树(专门用来查找)
    Unity可视化Shader工具ASE介绍——4、ASE的自定义模板使用
    【基于simulink的二阶电路仿真】
    Node.js:Jest测试框架
    回归分析中的异方差性
    共享虚拟主机可以处理多少流量?
    Java LinkedList类详解
    【二十四】springboot使用EasyExcel和线程池实现多线程导入Excel数据
    Sentinel规则持久化到Nacos教程
    Java 华为真题-选修课
  • 原文地址:https://blog.csdn.net/weixin_47436633/article/details/133900423