gpt4 book ai didi

javascript - d3 : Smoothly animate a hand drawn line?

转载 作者:搜寻专家 更新时间:2023-11-01 05:23:27 25 4
gpt4 key购买 nike

请参阅this pen对于我想要的一个工作但简陋的版本:一个 d3 动画,实时模拟一个人画的线的路径。

我当前的实现有两个问题:

  1. 天气不稳定。您可以看到路径的每一部分都显示为一个 block ,而不是看起来像是在屏幕上移动的笔的路径。一种解决方案是让每个 block 更小——还有其他解决方案吗?

  2. 它是递归的。使用 setTimeout() 递归调用绘制感觉与 d3 精神背道而驰。是否有更具声明性的解决方案?也许一个使用 transition()

Javascript

var svg = d3.select("body").append("svg")
.attr("width", "100%")
.attr("height", "100%");


var lineData = d3.range(5,800,15).map(function(x) {
return {x: x, y: 10 + Math.floor(Math.random()*6)-3}
});

var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("basis");

function draw(points) {

var lineGraph = svg.append("path")
.attr("stroke", "blue")
.attr("stroke-width", 1)
.attr("fill", "none")
.attr("d", lineFunction(points));

if (points.length < lineData.length)
setTimeout(function(){
draw(lineData.slice(0,points.length+1));
}, 50);
}

draw([]);

最佳答案

See this simple (and neat) trick使用 stroke-dasharray 逐渐为路径的绘制设置动画。这是 your code, modified .

var lineGraph = svg
.append("path")
.attr("stroke", "blue")
.attr("stroke-width", 1)
.attr("fill", "none")
.attr("d", lineFunction(lineData))
.transition()
.duration(5000)
.attrTween("stroke-dasharray", tweenDash)

function tweenDash() {
var l = this.getTotalLength(),
i = d3.interpolateString("0," + l, l + "," + l);
return function(t) { return i(t); };
}

关于javascript - d3 : Smoothly animate a hand drawn line?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20695723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com