微信小程序使用图片实现红包雨功能

微信小程序红包雨功能实现:从组件封装到页面调用的完整实践

先看示例截图:

一、背景与技术选型

在微信小程序营销活动中,红包雨是一种极具吸引力的互动形式。实现红包雨效果主要有 Canvas 和图片两种方案:

(1)Canvas 方案:性能优异,资源占用小,但视觉表现依赖绘图 API

(2)图片方案:视觉效果真实,可灵活设计红包样式,但资源加载与内存占用较高

本文将采用图片方案实现红包雨组件,通过组件化设计提升代码复用性,并分享性能优化经验,帮助开发者在真实感与性能间找到平衡点。
二、组件设计与实现
2.1 组件结构设计

首先创建组件文件夹components/img-rain,目录结构如下:

bash 复制代码
components/
└─ img-rain/
   ├── index.js         // 逻辑层
   ├── index.wxml       // 视图层
   ├── index.wxss       // 样式层
   ├── index.json       // 配置文件
   └── images/             // 红包图片资源
       ├── img1.png
       ├── img2.png
       └── img3.png

2.2 组件核心代码实现

以下是图片红包雨组件的完整实现:

javascript 复制代码
Component({
  properties: {
    petalCount: {
      type: Number,
      value: 60
    },
    speed: {
      type: Number,
      value: 2
    },
    wind: {
      type: Number,
      value: 0.3
    },
    images: {
      type: Array,
      value: [
        '/images/5.png',
        '/images/100.png',
        '/images/500.png',
        '/images/1000.png'
      ]
    }
  },

  data: {
    petals: []
  },

  lifetimes: {
    attached() {
      this.createPetals();
      this.startAnimation();
    },
    detached() {
      this.stopAnimation();
    }
  },

  methods: {
    createPetals() {
      const {
        petalCount,
        images
      } = this.properties;
      const {
        windowWidth,
        windowHeight
      } = wx.getWindowInfo();
      const petals = [];

      for (let i = 0; i < petalCount; i++) {
        const size = 40 + Math.random() * 20;
        const left = Math.random() * (windowWidth - size);
        const top = -size - Math.random() * windowHeight;
        petals.push({
          id: `petal-${i}`,
          image: images[Math.floor(Math.random() * images.length)],
          x: left,
          y: top,
          size,
          speed: 5 + Math.random() * this.properties.speed,
          windEffect: (Math.random() - 0.5) * this.properties.wind
        });
      }
      this.setData({
        petals
      });
    },
    // 开始动画
    startAnimation() {
      const {
        windowHeight
      } = wx.getWindowInfo();
      this.animationInterval = setInterval(() => {
        this.setData({
          petals: this.data.petals.map(petal => {
            // 更新位置和旋转
            petal.y += petal.speed;
            petal.x += petal.windEffect;
            // 如果花瓣超出屏幕,重置到顶部
            if (petal.y > windowHeight + petal.size || petal.x < -petal.size || petal.x > wx.getWindowInfo().windowWidth + petal.size) {
              petal.y = -petal.size - Math.random() * windowHeight;
              petal.x = Math.random() * (wx.getWindowInfo().windowWidth - petal.size);
            }
            return petal;
          })
        });
      }, 30); // 约30ms一帧
    },

    // 停止动画
    stopAnimation() {
      if (this.animationInterval) {
        clearInterval(this.animationInterval);
      }
    },
  }
});

2.3 视图层实现

xml 复制代码
<view class="rain-container">
  <image wx:for="{{petals}}" wx:key="id" src="{{item.image}}" style="position: fixed;left: {{item.x}}px;top: {{item.y}}px;width: {{item.size}}px;height: {{item.size+20}}px;pointer-events: none;z-index: -1;"></image>
</view>

2.4 样式层实现

css 复制代码
.rain-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 9998;
  overflow: hidden;
}

三、页面调用与集成
3.1 页面配置

在需要调用的界面的json文件处引入组件

javascript 复制代码
{
  "usingComponents": {
    "img-rain": "/components/img-rain/index"
  },
  "navigationStyle": "custom"
}

3.2 页面布局

xml 复制代码
<img-rain petalCount="10" speed="0" wind="0."></img-rain>

四、总结与拓展

本文通过组件化设计实现了微信小程序中基于图片的红包雨效果,兼顾了视觉真实感与代码复用性。实际项目中,可根据活动预算和性能要求选择合适的实现方案:

(1)对性能要求高、视觉要求低的场景推荐使用 Canvas 方案

(2)对视觉效果要求高、预算充足的场景推荐使用图片方案

编写不易,谢谢点赞+收藏+关注,后续更新更多示例呦~

相关推荐
海兰7 小时前
【应用】基于 Next.js 16 + Python mplfinance的金融K线图与技术指标可视化平台(三)
javascript·python·金融
小磊哥er9 小时前
深入解构Claude Code - 第 7 篇 · 连接外面的世界
javascript·ai编程
小磊哥er9 小时前
深入解构Claude Code - 第 6 篇 · 终端里的图形界面
javascript·ai编程
海兰9 小时前
【应用】基于 Next.js 16 + Python mplfinance的金融K线图与技术指标可视化平台(一)
javascript·python·金融
软件聚导航10 小时前
「聚小软 AI 助手」技术升级:从数据库检索到 RAG 知识库问答
前端·数据库·mysql·微信小程序·小程序·ai编程·rag
可乐鸡翅yeah_10 小时前
hls.js 内存泄漏实战排查,直播 M3U8 长时间播放异常定位方案
开发语言·javascript·python·django·ecmascript·m3u8·m3u8在线
可乐鸡翅yeah_10 小时前
第三方接口对接 M3U8 流媒体排坑实战,解决外部服务商流兼容难题
前端·javascript·python·django·html·m3u8·m3u8在线
默_笙11 小时前
🏠 「LLM Notes」:我用 Next.js + Redis 给自己造了个笔记博客
前端·javascript
ruanCat13 小时前
Prettier 明明执行成功,Markdown 为什么还是没变?一次插件误诊复盘
前端·javascript·node.js
软件开发技术深度爱好者13 小时前
在线学习实践 TypeScript 的官方Playground(演练场)使用介绍
javascript·学习·typescript