当前位置: 首页> 科技> 数码 > 不囤货的网店怎么开_webqq网页版_网络营销广告策划_企业网站制作费用

不囤货的网店怎么开_webqq网页版_网络营销广告策划_企业网站制作费用

时间:2025/9/11 21:25:21来源:https://blog.csdn.net/ace15824843202/article/details/147143774 浏览次数:0次
不囤货的网店怎么开_webqq网页版_网络营销广告策划_企业网站制作费用

安装核心依赖

npm install lottie-miniprogram @tarojs/plugin-html --save

修改 Taro 配置 (config/index.js)

const config = {plugins: ['@tarojs/plugin-html',// 其他插件...],mini: {canvas: true,webpackChain(chain) {chain.merge({module: {rule: {'lottie-loader': {test: /\.json$/,use: {loader: 'lottie-miniprogram/webpack-loader',options: {limit: 10240 // 10KB以下文件直接内联}}}}}})}}
}

app.config.js里添加配置

export default defineAppConfig({// 其他代码...requiredBackgroundModes: ['canvas'],// 其他代码...})

封装组件commonLottie

import React, { useEffect, useRef, useState } from 'react'
import Taro, { createSelectorQuery } from '@tarojs/taro'
import { View, Canvas } from '@tarojs/components'const CommonLottie = React.forwardRef(({animationData,width = 24,height = 24,loop = false,autoplay = true,canvasId = 'lottie-canvas' // 新增动态 ID 支持},ref) => {const canvasRef = useRef(null)const lottieInstance = useRef(null)const animationDuration = useRef(1500) // 固定1秒时长// 暴露方法给父组件React.useImperativeHandle(ref, () => ({play: () => {if (lottieInstance.current) {// 先重置再播放lottieInstance.current.goToAndStop(0, true)lottieInstance.current.play()}},pause: () => lottieInstance.current?.pause()}))const calculateSizes = () => {//   const systemInfo = Taro.getSystemInfoSync()const dpr = 1// 逻辑尺寸 → 物理像素尺寸const physicalWidth = width * dprconst physicalHeight = height * dpr// Lottie 内部使用逻辑单位,需要反向缩放const lottieWidth = width / dprconst lottieHeight = height / dprreturn {physicalWidth,physicalHeight,lottieWidth,lottieHeight,dpr}}// 使用重构后的尺寸配置const { physicalWidth, physicalHeight, lottieWidth, lottieHeight, dpr } =calculateSizes()// 微信小程序专属初始化逻辑const initWechatCanvas = async () => {try {// 使用 Taro.nextTick 确保 DOM 更新完成await new Promise((resolve) => Taro.nextTick(resolve))// 增加重试次数和间隔let retryCount = 0const MAX_RETRY = 5const getNode = () =>new Promise((resolve, reject) => {createSelectorQuery().select(`#${canvasId}`).fields({ node: true, size: true }).exec((res) => {if (res[0]?.node) resolve(res[0].node)else if (retryCount < MAX_RETRY) {retryCount++setTimeout(() => getNode().then(resolve).catch(reject),200 * retryCount)} else {reject(new Error(`Canvas 节点未找到 (ID: ${canvasId})`))}})})const node = await getNode()//动态加载 Lottieconst Lottie = await import('lottie-miniprogram')// 计算播放速度const originalDuration =((animationData.op - animationData.ip) / animationData.fr) * 1000const playSpeed = originalDuration / animationDuration.current//创建动画实例lottieInstance.current = Lottie.loadAnimation({canvas: node,renderer: 'canvas',animationData,loop,autoplay,rendererSettings: {context: node.getContext('2d'),dpr: 1,scaleMode: 2, // 1: 按比例填充容器,2: 完全填充preserveAspectRatio: 'xMidYMid meet' // 保持宽高比}})// 新增适配逻辑const animation = lottieInstance.currentanimation.resize(lottieWidth, lottieHeight) // 强制刷新尺寸animation.setSubframe(false) // 关闭子帧优化// 设置播放速度animation.setSpeed(playSpeed)// 自动销毁// animation.addEventListener('complete', () => {//   animation.destroy()// })} catch (err) {console.error('初始化失败:', err)}}useEffect(() => {if (process.env.TARO_ENV !== 'weapp') returnif (!animationData) returnconst timer = setTimeout(() => {initWechatCanvas()}, 300) // 增加初始化延迟return () => {clearTimeout(timer)lottieInstance.current?.destroy()}}, [animationData])return (<Viewstyle={{width: `${width}px`,height: `${height}px`,overflow: 'visible',// 修复定位问题position: 'relative'}}><Canvasid={canvasId}canvasId={canvasId} // 必须同时设置 id 和 canvasIdtype="2d"style={{width: `${physicalWidth}px`,height: `${physicalHeight}px`,transform: `translateZ(0)`, // 强制启用 GPU 加速transformOrigin: '0 0',imageSmoothingQuality: 'high' // 高清渲染}}ref={canvasRef}/></View>)}
)export default CommonLottie

页面中使用

import { View, Button, Image, Text, WebView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState, useEffect, useRef } from 'react'
import './index.module.less'
import styles from './index.module.less'
import animationData from '@/assets/doc/tab_2_on.json'
import CommonLottie from '@/components/commonLottie'definePageConfig({navigationStyle: 'custom',backgroundColor: '#191919'
})export default function ExperiencePage() {const lottieRef = useRef(null)const play = () => {lottieRef.current.play()console.log(' lottieRef.current', lottieRef.current)}return (<View className={styles['experience-wrap']}><Button onClick={play}>按钮</Button><CommonLottieref={lottieRef}canvasId={'lottie-canvas-test'}animationData={animationData}width={36}height={24}/></View>)
}
关键字:不囤货的网店怎么开_webqq网页版_网络营销广告策划_企业网站制作费用

版权声明:

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

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

责任编辑: