首页 > 解决方案 > 通过 CSS 过渡动画 SVG 直线

问题描述

我想以相同的方式移动线条和圆圈,并使用 CSS 为过渡设置动画。
它适用于圈子,而不是线条。

怎么了 ?

const state = {
  x: 75,
  y: 75
};
const line = document.getElementsByTagName('line')[0];
const circle = document.getElementsByTagName('circle')[0];

setInterval(() => {
  state.x = Math.floor(Math.random() * 150);
  state.y = Math.floor(Math.random() * 150);
  line.setAttribute("x2", state.x);
  line.setAttribute("y2", state.y);
  circle.setAttribute("transform", `translate(${state.x} ${state.y})`);
}, 2000)
circle,
line {
  transition: all 1s ease;
}
<svg height="150" width="150" style="border: 1px solid black">
  <line 
    x1="0"
    y1="0"
    x2="75"
    y2="75"
    stroke="red"
  >
  </line>
  <circle 
    r="10"
    transform="translate(75 75)"
    fill="none"
    stroke="blue"
  >
  </circle>
</svg>

标签: csssvgcss-animationscss-transitionssvg-animate

解决方案


您可以使用 Path 元素代替 Line 元素,如下所示:

const state = {
  x: 75,
  y: 75
};
const line = document.getElementsByClassName('line')[0];

setInterval(() => {
  state.x = Math.floor(Math.random() * 150);
  state.y = Math.floor(Math.random() * 150);
  line.setAttribute("d", `M 0 0 l ${state.x} ${state.y}`);
}, 2000)
path {
  transition: all 1s ease;
}
<svg height="150" width="150" style="border: 1px solid black">
    <path
    class="line"
    d="M 0 0 L 75 75"
    stroke="red"
    fill="none"
    />
</svg>


推荐阅读