如何制作交互式和动画的SVG折线图表

3

我正在尝试使用SVG和polyline制作图表,并为其分配点。这一部分没有问题,但是由于我对Web开发还很陌生,我在制作交互式内容时遇到了困难。

我想在鼠标悬停在某个X值上时,在工具提示中显示该点的Y值。我已经成功创建了工具提示,但不知道如何获取Y值,是否有好的方法可以做到这一点?

另外,我正在尝试对polyline进行动画处理,使其看起来像是实际绘制出来的,而不仅仅是在读取坐标后出现在屏幕上。我在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';

这是路径动画代码的样子,但由于某些原因,在折线上无法正常工作。这是因为路径不等于折线吗?

1个回答

1

我正在做类似的事情,但我还没有解决工具提示。不过,我有一个基于你参考的同一篇博客文章的动画折线的工作示例。

唯一的区别是,我使用了style.webkitTransition(注意小写的w),而你的代码使用了style.WebkitTransition。我注意到在这个答案中也有同样的差异。也许自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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接