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

api部分

javascript 复制代码
export function getRainInfo() {
  return onlineRequest({
    url: '/ball/recruit/getRainInfo',
    method: 'get'
  });
}

data存储json数据

javascript 复制代码
data:{
	rainJson:{}
}

onLoad方法获取json数据

javascript 复制代码
onLoad(options) {
  let that = this
  getRainInfo().then((res)=>{
    that.setData({
      rainJson:res
    })
  })
}

initLottie动画方法

javascript 复制代码
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接口返回

java 复制代码
 @GetMapping("/getRainInfo")
 public String getRainInfo() throws IOException {
     // 读取JSON文件
     return readJsonFile("rain.json");
 }

如果到这里还不显示,那么就是你们页面的层级有问题,把动画页面设置成z-index:999999最大

html 复制代码
<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事件不触发

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

相关推荐
说私域5 小时前
新零售视域下实体与虚拟店融合的技术逻辑与商业模式创新——基于开源AI智能名片与链动2+1模式的S2B2C生态构建
人工智能·小程序·开源·零售
像素之间5 小时前
微信小程序中安装vant
微信小程序
java1234_小锋6 小时前
[免费]微信小程序音乐播放器(爬取网易云音乐数据)(node.js后端)【论文+源码】
微信小程序·小程序·node.js·音乐播放器·网易云音乐
野盒子6 小时前
前端面试题 微信小程序兼容性问题与组件适配策略
前端·javascript·面试·微信小程序·小程序·cocoa
胡斌附体7 小时前
uniapp小程序不支持动态组件问题
小程序·uni-app·if-else·动态组件·不支持·编译异常
小妖6667 小时前
uni-app 小程序 Cannot read property ‘addEventListener‘ of undefined, mounted hook
小程序·uni-app
二倍本贝9 小时前
【慧游鲁博】【12】小程序端 · 智能导览对接后端文物图片识别功能
小程序·uni-app·vue·软件工程
weixin_ab9 小时前
小程序【页面离开、页面卸载】对比区分
小程序
Maitians16 小时前
微信小程序 - 保存手机号等信息到通讯录
微信小程序·小程序
Maitians18 小时前
微信小程序 - 手机震动
微信小程序·小程序