LeaferJS实现线条动画[支持元素编辑]

0 阅读1分钟

相关原理参考: www.leaferjs.com/ui/referenc…

  • getMotionTotal 获取元素路径总长度
  • getMotionPoint 获取长度在路径上的具体坐标
  • Platform.requestRender(animate) 类似于浏览器的requestAnimationFrame
  • app.editor.on(EditorScaleEvent.SCALE, (e) => { line.__.__pathForMotion=null })实现元素scale时清除路径数据缓存,在源码中一次通过getMotionTotal会缓存得到的路径数据,所以在编辑器元素scale时需要重新计算,否则会导致动画长度与实际长度不匹配
import { Leafer, Rect, Line, App, Ellipse, Platform } from 'leafer-ui'
import '@leafer-in/editor'
import '@leafer-in/motion-path'
import { EditorScaleEvent } from '@leafer-in/editor'
import { HighCurveHelper } from '@leafer-in/motion-path'
const app = new App({ view: window, editor: {} })

const rect = new Rect({
  x: 100,
  y: 100,
  width: 100,
  height: 100,
  fill: '#32cd79',
  editable: true,
})
const ellipse = new Ellipse({
  width: 10,
  height: 10,
  fill: '#32cd79',
  around: 'center',
})
const line = new Line({
  toPoint: { x: 100, y: 50 },
  strokeWidth: 5,
  stroke: '#32cd79',
  editable: true,
})
app.tree.add(ellipse)
app.tree.add(line)

app.tree.add(rect)

console.log(line.getMotionTotal())
let to = 0
// 3. 循环飞行动画
function animate() {
  to += 2
let total = line.getMotionTotal()

  if (to > total) to = 0
  const { x, y, rotation } = line.getMotionPoint(to)
  ellipse.set({ x, y, rotation })
  Platform.requestRender(animate)
}

animate()

app.editor.on(EditorScaleEvent.SCALE, (e) => {
  line.__.__pathForMotion=null
})

在这里插入图片描述


function getMotionPathData(leaf: IUI): IMotionPathData {
    const data = leaf.__
    if (data.__pathForMotion) return data.__pathForMotion
    return data.__pathForMotion = HighCurveHelper.getMotionPathData(leaf.getPath(true, true))
}