无法使用 D3 使路径绘制缓慢增长 [英] Can't make paths draw growing slowly with D3

查看:22
本文介绍了无法使用 D3 使路径绘制缓慢增长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 d3 图形库,我似乎无法使路径缓慢绘制,因此可以看到它们在增长.

本网站在折线图(展开)"部分,但没有给出该部分的代码.有人可以帮我写几行可以实现这一点的 D3 代码吗?

当我尝试在下面的代码片段中添加 delay() 或 duration() 时,路径仍然会立即绘制,并且此段之后的所有 SVG 代码都无法呈现.

 var mpath = svg.append('path');mpath.attr ('d', 'M35 48 L22 48 L22 35 L22 22 L35 22 L35 35 L48 35 L48 48').attr ('填充', '无').attr ('中风', '蓝色').duration (1000);

解决方案

我相信D3 方式"可以使用自定义的补间函数.你可以在这里看到一个有效的实现:http://jsfiddle.net/nrabinowitz/XytnD/>

这假设您有一个名为 line 的生成器,它设置了 d3.svg.line 来计算路径:

//添加元素和过渡var path = svg.append('path').attr('class', 'line').attr('d', line(data[0])).过渡().duration(1000).attrTween('d', pathTween);函数 pathTween() {var 插值 = d3.scale.quantile().domain([0,1]).range(d3.range(1, data.length + 1));返回函数(t){返回行(data.slice(0,插值(t)));};}

此处的 pathTween 函数返回一个插值器,该插值器采用给定的线段(由我们通过过渡的距离定义),并相应地更新路径.

不过,值得注意的是,我怀疑您可以通过以下简单的方法获得更好的性能和更流畅的动画:放置一个白色矩形(如果您的背景很简单)或一个 clipPath(如果您的背景很复杂)在线上,然后将其向右过渡以显示下面的线.

Using the d3 graphics library, I can't seem to make paths draw slowly so they can be seen growing.

This site has a perfect example in the "Line Chart (Unrolling)" section, but no code is given for that section. Could someone please help me with the lines of D3 code that could make that happen?

When I try appending delay() or duration() such as in the following code snippet, the path still draws immediately, And all the SVG code after this segment fails to render.

    var mpath = svg.append ('path');
        mpath.attr ('d', 'M35 48 L22 48 L22 35 L22 22 L35 22 L35 35 L48 35 L48 48')
             .attr ('fill', 'none')
             .attr ('stroke', 'blue')
             .duration (1000);

解决方案

I believe the "D3 way" to do this is with a custom tween function. You can see a working implementation here: http://jsfiddle.net/nrabinowitz/XytnD/

This assumes that you have a generator called line set up with d3.svg.line to calculate the path:

// add element and transition in
var path = svg.append('path')
    .attr('class', 'line')
    .attr('d', line(data[0]))
  .transition()
    .duration(1000)
    .attrTween('d', pathTween);

function pathTween() {
    var interpolate = d3.scale.quantile()
            .domain([0,1])
            .range(d3.range(1, data.length + 1));
    return function(t) {
        return line(data.slice(0, interpolate(t)));
    };
}​

The pathTween function here returns an interpolator that takes a given slice of the line, defined by how far we are through the transition, and updates the path accordingly.

It's worth noting, though, that I suspect you'd get better performance and a smoother animation by taking the easy route: put a white rectangle (if your background is simple) or a clipPath (if your background is complex) over the line, and transition it over to the right to reveal the line underneath.

这篇关于无法使用 D3 使路径绘制缓慢增长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆