微信小程序使用畫布實現飄落泡泡功能:從組件封裝到頁面調用的完整實踐
先看示例截圖:
一、背景與技術選型
在微信小程序中實現類似于飄落的泡泡或者櫻花飄落的功能,一般主要有 Canvas 和圖片兩種方案:
(1)Canvas 方案:性能優異,資源占用小,但視覺表現依賴繪圖 API
(2)圖片方案:視覺效果真實,但資源加載與內存占用較高
本文將采用Canvas 方案實現飄落的泡泡組件,通過組件化設計提升代碼復用性,并分享性能優化經驗,幫助開發者在真實感與性能間找到平衡點。
二、組件設計與實現
2.1 組件結構設計
首先創建組件文件夾components/down-rain,目錄結構如下:
components/
└─ down-rain/├── index.js // 邏輯層├── index.wxml // 視圖層├── index.wxss // 樣式層├── index.json // 配置文件
2.2 組件核心代碼實現
以下是組件的完整實現:
Component({properties: {// 數量petalCount: { type: Number, value: 60 },// 大小petalSize: { type: Array, value: [3, 8] },// 下落速度speed: { type: Number, value: 2 },// 風力影響wind: { type: Number, value: 0.3 },},data: {canvasWidth: 0,canvasHeight: 0,ctx: null,animationTimer: null,petals: []},lifetimes: {attached() {this.initCanvas();},detached() {this.stopAnimation();}},methods: {// 初始化Canvasasync initCanvas() {const query = this.createSelectorQuery();query.select('.canvas').boundingClientRect();const { windowWidth, windowHeight } = wx.getSystemInfoSync();const canvas = wx.createCanvasContext('downCanvas', this);this.setData({canvasWidth: windowWidth,canvasHeight: windowHeight,ctx: canvas,petals: this.createPetals()});this.startAnimation();},// 創建花瓣數組 - 修改:從隨機位置開始下落createPetals() {const { petalCount, petalSize } = this.properties;const { canvasWidth, canvasHeight } = this.data;const vanishLine = canvasHeight * 2 / 3; // 消失線位置return Array(petalCount).fill().map(() => {// 隨機生成初始位置,y可以在畫布上方const y = Math.random() * canvasHeight * 1.5 - canvasHeight * 0.5;return {x: Math.random() * canvasWidth,y,size: petalSize[0] + Math.random() * (petalSize[1] - petalSize[0]),speed: 0.5 + Math.random() * this.properties.speed,angle: Math.random() * Math.PI * 2,wind: (Math.random() - 0.5) * this.properties.wind,alpha: 0.5 + Math.random() * 0.5,startY: y, // 記錄起始Y坐標用于計算消失visible: y < vanishLine // 初始可見性判斷};});},// 開始動畫startAnimation() {this.data.animationTimer = setInterval(() => {this.updatePetals();this.drawPetals();}, 30);},// 停止動畫stopAnimation() {if (this.data.animationTimer) {clearInterval(this.data.animationTimer);}},// 更新位置updatePetals() {const { canvasWidth, canvasHeight, petals } = this.data;const vanishLine = canvasHeight * 2 / 3; this.setData({petals: petals.map(petal => {petal.y += petal.speed;petal.x += Math.sin(petal.angle) * petal.wind;petal.angle += 0.02;// 計算與消失線的距離比例const distanceRatio = Math.max(0, (petal.y - vanishLine) / (canvasHeight - vanishLine));// 超過消失線后逐漸消失if (distanceRatio > 0) {petal.alpha = Math.max(0, petal.alpha * (1 - distanceRatio));petal.visible = petal.alpha > 0;} else {petal.visible = true;petal.alpha = 0.5 + Math.random() * 0.5; // 重置透明度}// 完全消失后重置位置if (!petal.visible || petal.y > canvasHeight) {return {x: Math.random() * canvasWidth,y: -10, // 從頂部重新開始size: petal.size, // 保持原有大小speed: 0.5 + Math.random() * this.properties.speed,angle: Math.random() * Math.PI * 2,wind: petal.wind, // 保持原有風力影響alpha: 0.5 + Math.random() * 0.5,startY: -10,visible: true};}return petal;})});},// 繪制drawPetals() {const { ctx, petals } = this.data;ctx.clearRect(0, 0, this.data.canvasWidth, this.data.canvasHeight);petals.forEach(petal => {if (petal.visible) {ctx.beginPath();ctx.arc(petal.x, petal.y, petal.size, 0, Math.PI * 2);ctx.fillStyle = `rgba(255, 192, 203, ${petal.alpha})`;ctx.fill();}});ctx.draw(false);},}
});
2.3 視圖層實現
<canvas class="canvas" canvas-id="downCanvas"></canvas>
2.4 樣式層實現
.canvas {position: fixed;top: 0;left: 0;width: 100%;height: 100%;pointer-events: none;z-index: 999;
}
三、頁面調用與集成
3.1 頁面配置
在需要調用的界面的json文件處引入組件
{"usingComponents": {"down-rain": "/components/down-rain/index"},"navigationStyle": "custom"
}
3.2 頁面布局
<down-rain petalCount="50" speed="5"></down-rain>
四、總結與拓展
本文通過組件化設計實現了微信小程序中基于Canvas 的飄落泡泡的效果。實際項目中,可根據活動預算和性能要求選擇合適的實現方案:
(1)對性能要求高、視覺要求低的場景推薦使用 Canvas 方案
(2)對視覺效果要求高、預算充足的場景推薦使用圖片方案
編寫不易,謝謝點贊+收藏+關注,后續更新更多示例呦~