[英]draw circle in the end of SVG path in realtime line chart D3.js
我需要在实时折线图中的SVG路径的末尾绘制圆圈。 我使用d3.js绘制图表。 一切都很好,但是这个麻烦使我困惑。
请告诉我代码中的错误,并帮助我找到更好的解决方案。
谢谢!
JS代码:
var GraphIndex = (function() {
var n = 10,
duration = 15000,
now = new Date(Date.now() - duration),
random = d3.random.normal(0, 100),
data = d3.range(n).map(random);
var width = 379,
height = 138;
// X axis
var x = d3.time.scale()
.domain([now - (n - 2) * duration, now - duration])
.range([0, width - 40]);
// Y axis
var y = d3.scale.linear()
.domain([(-1)*d3.max(data) - 100, d3.max(data) + 100])
.range([height, 0]);
var line = d3.svg.line()
.interpolate("linear")
.x(function(d, i) { return x(now - (n - 1 - i) * duration); })
.y(function(d, i) { return y(d); });
var svg = d3.select(".graph-holder").append("svg")
.attr("width", width)
.attr("height", height + 30);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width - 40)
.attr("height", height);
// X Axis
var axis = svg.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + height + ")")
.call(x.axis = d3.svg.axis().scale(x).orient("bottom").ticks(d3.time.minutes, 1));
// Line
var path = svg.append("g")
.attr("clip-path", "url(#clip)")
.attr("class", "path-area")
.append("path")
.data([data])
.attr("class", "line")
.attr("id", "myPath");
//Draw the Circle
var circle = d3.select(".path-area")
.append("svg:circle")
.attr("cx", 335)
.attr("cy", y(data[n - 2]))
.attr("r", 4)
.attr("class", "circle");
this.tick = (function(){
now = new Date();
x.domain([now - (n - 2) * duration, now - duration]);
y.domain([(-1)*d3.max(data) - 100, d3.max(data) + 100]);
var d = random()
data.push(d);
// redraw the line
svg.select(".line")
.attr("d", line)
.attr("transform", null);
// slide the x-axis left
axis.transition()
.duration(duration)
.ease("linear")
.call(x.axis);
// slide the line left
path.transition()
.duration(duration)
.ease("linear")
.attr("transform", "translate(" + x(now - (n - 1) * duration) + ")")
.each("end", tick);
circle.transition()
.duration(duration)
.ease("linear")
.attr("transform", "translate(0, " + y(d) + ")");
// pop the old data point off the front
data.shift();
});
this.tick();
});
GraphIndex();
HTML代码:
<div class="graph-holder"></div>
CSS代码:
.graph-holder {
position: relative;
width: 379px; height: 138px;
}
.x-axis line {
shape-rendering: auto;
stroke-width: 2px;
}
.x-axis path,
.x-axis line {
fill: none;
stroke: none;
shape-rendering: crispEdges;
}
.x-axis .tick {
color: #fff;
stroke: #fff;
font-size: .75em;
}
.line {
fill: none;
stroke: #fff;
stroke-width: 2.5px;
}
circle {
fill: #fff;
}
您是否尝试过调整圆的cy
而不是平移它? 您的Y轴未链接,因此无需变换坐标系。
所以代替
.attr("transform", "translate(0, " + y(d) + ")");
尝试
.attr("cy", function() { return y(data[data.length-2]); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.