因此,我正在尝试使用我分配点的 SVG 和折线制作图表。那部分不是问题,而是新的,因为我在 web 开发中,我正在努力让它具有交互性。 我希望它在工具提示中的某个 X 值处显示鼠标悬停时的 Y 值。我设法创建了一个工具提示,但不知道如何获取 Y 值,那么有什么好的方法吗?
我正在尝试做的另一件事是为多段线设置动画,使其看起来像是实际绘制的,而不是在读取坐标后才出现在屏幕上。我在这里为 SVG 中的路径找到了类似的东西:https://jakearchibald.com/2013/animated-line-drawing-svg/
var path = document.querySelector('.squiggle-animated path');
var length = path.getTotalLength();
// Clear any previous transition
path.style.transition = path.style.WebkitTransition =
'none';
// Set up the starting positions
path.style.strokeDasharray = length + ' ' + length;
path.style.strokeDashoffset = length;
// Trigger a layout so styles are calculated & the browser
// picks up the starting position before animating
path.getBoundingClientRect();
// Define our transition
path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset 2s ease-in-out';
// Go!
path.style.strokeDashoffset = '0';
这是路径动画代码的样子,但由于某些原因它不适用于多段线。给出该路径不等于折线是否有特定原因?
最佳答案
我自己也在做类似的事情,但我还没有处理工具提示。但是,我确实有一个基于您引用的同一篇博客文章的动画多段线的工作示例。
我能看到的唯一区别是我使用的是 style.webkitTransition
(注意小 w
),而您的代码有 style.WebkitTransition
。我注意到了相同的差异 in this answer.也许自 2013 年以来的某个时候,该 CSS 属性的名称已用小写字母标准化。
function cssAnimate() {
var polyline = document.getElementById('plotLine');
var length = polyline.getTotalLength();
// Clear any previous transition
polyline.style.transition = polyline.style.webkitTransition = 'none';
// Set up the starting positions
polyline.style.strokeDasharray = length + ' ' + length;
polyline.style.strokeDashoffset = length;
// Trigger a layout so styles are calculated & the browser
// picks up the starting position before animating
polyline.getBoundingClientRect();
// Define our transition
polyline.style.transition = polyline.style.webkitTransition = 'stroke-dashoffset 3s ease-in-out';
// Go!
polyline.style.strokeDashoffset = '0';
}
cssAnimate();
<html>
<svg id="plot" viewBox="0 0 100 100" class="chart">
<polyline
id="plotLine"
fill="none"
stroke="#0074d9"
stroke-width="1"
stroke-dasharray=""
stroke-dashoffset="0.00"
points="
00,50
10,70
20,35
30,65
40,77
50,91
"
/>
</svg>
</body>
</html>
关于javascript - 如何制作交互式动画 SVG 折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38630313/