api部分
export function getRainInfo() {return onlineRequest({url: '/ball/recruit/getRainInfo',method: 'get'});
}
data存儲json數據
data:{rainJson:{}
}
onLoad方法獲取json數據
onLoad(options) {let that = thisgetRainInfo().then((res)=>{that.setData({rainJson:res})})
}
initLottie動畫方法
initLottie(url, type) {// 1. 銷毀舊動畫if (this.anim) {this.anim = null;}// 2. 更新顯示狀態this.setData({rainShow: type === 'rain',snowShow: type === 'snow'}, () => {// 3. 在setData回調中確保DOM已更新const selector = type === 'rain' ? '#lottie-animation-rain' : '#lottie-animation-snow';// wx.showToast({ title: selector });wx.createSelectorQuery().in(this).select(selector).node().exec((res) => {if (!res[0] || !res[0].node) {console.error('未找到Canvas節點,選擇器:', selector);return;}const canvas = res[0].node;const ctx = canvas.getContext('2d');// 清空畫布ctx.clearRect(0, 0, canvas.width, canvas.height);canvas.width = canvas.width; // 強制重置畫布// 加載新動畫this.anim = lottie.loadAnimation({loop: true,autoplay: true,// path:url, //注釋這個,這個在真機不會顯示!animationData: this.data.rainJson, //必須使用animationData,從后端返回json數據rendererSettings: {context: ctx}});});});
}
注意了!
path:url
, 這個在真機不會顯示!
animationData: this.data.rainJson
, 必須使用animationData,從后端返回json數據
后端部分,把json文件放到resource里面
通過getRainInfo接口返回
@GetMapping("/getRainInfo")public String getRainInfo() throws IOException {// 讀取JSON文件return readJsonFile("rain.json");}
如果到這里還不顯示,那么就是你們頁面的層級有問題,把動畫頁面設置成z-index:999999最大
<view style="z-index: 9999999;"><canvas id="lottie-animation-rain" hidden="{{!rainShow}}" type="2d" style="position: fixed;top:0;left:0;width: 100%;height: {{margintop+140}}px;z-index: 9999999;pointer-events: none"></canvas><canvas id="lottie-animation-snow" hidden="{{!snowShow}}" type="2d" style="position: fixed;top:0;left:0;width: 100%;height: {{margintop+140}}px;z-index: 9999999;pointer-events: none"></canvas>
</view>
pointer-events: none主要是防止其他view事件不觸發