微信小程序紅包雨功能實現:從組件封裝到頁面調用的完整實踐
先看示例截圖:
一、背景與技術選型
在微信小程序營銷活動中,紅包雨是一種極具吸引力的互動形式。實現紅包雨效果主要有 Canvas 和圖片兩種方案:
(1)Canvas 方案:性能優異,資源占用小,但視覺表現依賴繪圖 API
(2)圖片方案:視覺效果真實,可靈活設計紅包樣式,但資源加載與內存占用較高
本文將采用圖片方案實現紅包雨組件,通過組件化設計提升代碼復用性,并分享性能優化經驗,幫助開發者在真實感與性能間找到平衡點。
二、組件設計與實現
2.1 組件結構設計
首先創建組件文件夾components/img-rain,目錄結構如下:
components/
└─ img-rain/├── index.js // 邏輯層├── index.wxml // 視圖層├── index.wxss // 樣式層├── index.json // 配置文件└── images/ // 紅包圖片資源├── img1.png├── img2.png└── img3.png
2.2 組件核心代碼實現
以下是圖片紅包雨組件的完整實現:
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 視圖層實現
<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 樣式層實現
.rain-container {position: fixed;top: 0;left: 0;width: 100%;height: 100%;pointer-events: none;z-index: 9998;overflow: hidden;
}
三、頁面調用與集成
3.1 頁面配置
在需要調用的界面的json文件處引入組件
{"usingComponents": {"img-rain": "/components/img-rain/index"},"navigationStyle": "custom"
}
3.2 頁面布局
<img-rain petalCount="10" speed="0" wind="0."></img-rain>
四、總結與拓展
本文通過組件化設計實現了微信小程序中基于圖片的紅包雨效果,兼顧了視覺真實感與代碼復用性。實際項目中,可根據活動預算和性能要求選擇合適的實現方案:
(1)對性能要求高、視覺要求低的場景推薦使用 Canvas 方案
(2)對視覺效果要求高、預算充足的場景推薦使用圖片方案
編寫不易,謝謝點贊+收藏+關注,后續更新更多示例呦~