欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 微信小程序中,解决lottie动画在真机不显示的问题

微信小程序中,解决lottie动画在真机不显示的问题

2025/5/23 20:05:55 来源:https://blog.csdn.net/weixin_44912902/article/details/148123823  浏览:    关键词:微信小程序中,解决lottie动画在真机不显示的问题

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事件不触发

完成上面步骤真机就可以显示出来了!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词