You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Anime.js:实现循环双向运动时保持相同透明度过渡

解决Anime.js路径往返时透明度均从1到0的问题

问题描述

需要实现方块沿SVG路径往返移动时,透明度都从1过渡到0,但默认direction: 'alternate'设置下,正向移动透明度1→0,反向时会自动变为0→1,不符合需求。尝试用时间线分别添加正向、反向动画,但因direction参数仅能作用于时间线本身,导致反向动画的路径与透明度设置失效。

原默认效果代码:

anime({
  targets: ".square",
  translateX: path("x"),
  translateY: path("y"),
  rotate: path("angle"),
  opacity: [1, 0],
  loop: true,
  direction: 'alternate',
  easing: 'linear'
})

尝试的无效时间线代码:

anime.timeline({
  loop: true,
  duration: duration,
  })
  .add({
    targets: ".square",
    translateX: path("x"),
    translateY: path("y"),
    rotate: path("angle"),
    opacity: [1, 0],
    loop: true,
    direction: 'normal',
    easing: 'linear'        
  }).add({
    targets: ".square",
    translateX: path("x"),
    translateY: path("y"),
    rotate: path("angle"),
    opacity: [1, 0],
    loop: true,
    direction: 'reverse',
    easing: 'linear',  
    duration: duration,
  });

解决方案

核心思路是不依赖direction: 'alternate',手动在时间线中定义两次路径动画:正向走路径+透明度1→0,反向走路径+透明度1→0。利用Anime.jspath()函数的第二个参数reverse控制路径方向,同时每次动画都显式设置透明度从1到0。

可行代码示例:

const duration = 2000;
const pathEl = document.querySelector('path');

anime.timeline({
  loop: true
})
.add({
  targets: ".square",
  translateX: anime.path(pathEl)('x'),
  translateY: anime.path(pathEl)('y'),
  rotate: anime.path(pathEl)('angle'),
  opacity: [1, 0],
  duration: duration,
  easing: 'linear'
})
.add({
  targets: ".square",
  // 第二个参数true表示反向沿路径移动
  translateX: anime.path(pathEl)('x', true),
  translateY: anime.path(pathEl)('y', true),
  rotate: anime.path(pathEl)('angle', true),
  opacity: [1, 0],
  duration: duration,
  easing: 'linear'
});

关键说明

  1. 移除时间线与单个动画的direction参数,避免自动反转属性值
  2. 反向动画中给path()传入第二个参数true,实现元素沿路径反向移动
  3. 两次动画均显式设置opacity: [1, 0],确保往返过程透明度均从1过渡到0
  4. 时间线设置loop: true,实现无限往返循环

内容的提问来源于stack exchange,提问作者Orpheus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 16:29:54