gpt4 book ai didi

javascript - d3.js 动画线条绘制发生在与预期相反的方向

转载 作者:行者123 更新时间:2023-11-29 16:57:59 25 4
gpt4 key购买 nike

我在 d3.js 中有一个简单的线图,我希望为线的绘制设置动画。 fiddle :here .动画方面有效,但我希望从左到右绘制线条,而不是像 fiddle 中那样从右到左绘制。为什么这条线是从头到尾画的而不是副

/*canvas setup*/
var margin = {top: 20, right: 20, bottom: 70, left: 100},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body").append("svg").attr("id","chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("class","container")
.attr("transform",translate(margin.left,margin.bottom));
function translate(a,b){
return "translate(" + a + "," + b + ")";
}
/*data*/

var data = [{
"time": "2013-03-12 15:09:04",
"value": "5"
}, {
"time": "2013-03-12 14:59:06",
"value": "65"
}, {
"time": "2013-03-12 14:49:04",
"value": "15"
}, {
"time": "2013-03-12 14:39:06",
"value": "25"
},{
"time": "2013-03-12 14:29:03",
"value": "5"
}];
/*end data*/

var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
data.forEach(function(d) {
d.time = parseDate(d.time);
d.value = +d.value;
});
//create scales
var xScale = d3.time.scale()
.range([0,width])
.domain(d3.extent(data,function(d){ return d.time})),
yScale = d3.scale.linear()
.range([height,0])
.domain([0,d3.max(data,function(d){ return +d.value})]);

//create axes
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickFormat(d3.time.format("%H:%m"));

//create line
var line = d3.svg.line()
.x(function(d){return xScale(d.time)})
.y(function(d){ return yScale(d.value)});

var _line; //path that will be appended to the chart

var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");

var _x = svg.append("g")
.attr("class","xAxis")
.attr("transform",translate(0,height))
.call(xAxis);
var _y = svg.append("g")
.attr("class","yAxis")
.call(yAxis);
//draw line
function drawLine(){
_line = svg.append("path")
.attr("d", line(data))
.attr("stroke", "steelblue")
.attr("stroke-width", "2")
.attr("fill", "none");

var totalLength = _line.node().getTotalLength();
_line.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(750)
.ease("swing")
.attr("stroke-dashoffset", 0);

}
setTimeout(function(){
drawLine();
},500)

最佳答案

线条是从右边开始动画的,因为你从 totalLength 到 0 的偏移量设置动画。因此你的动画起点是:线条从末端开始,你的动画结束是线条开始于真正的开始。您只需通过设置 .attr("stroke-dashoffset", -totalLength)

来扭转这个逻辑,让它以负偏移量开始

我更新了你的 fiddle有了这个小改动。

关于javascript - d3.js 动画线条绘制发生在与预期相反的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30790671/

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