css - 通过 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>
解决方案
您可以使用 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>
推荐阅读
- c - 如果结构值位于 c 中另一个结构数组中的结构数组中,您将如何访问它们?
- reactjs - 尝试使用反应在表中查找检查值的总和
- r - 使用 heatmaply 创建带有原始值/数据而不进行转换的热图?
- python - 有没有办法直接从 python 中的二进制文件加载变量?
- java - 在 RESTful API 中创建和验证实体模型及其 DTO 的正确方法是什么?
- excel - 将时间范围分成每行半小时
- angular - 如何结合两个 combineLatest?
- python - AttibuteError:“_AppCtxGlobals”对象没有属性“用户”
- html - 我们可以在html中对复选框进行分组吗
- django - 用于服务 Django 应用程序的 Apache 配置不起作用