Jim*_*y C 24 javascript svg d3.js
我有一个图表,我希望代表图形的线在svg区域顶部悬停时在x坐标处显示一个圆圈.该圆应遵循表示曲线的线的路径.问题是我不知道该怎么做.
下面的代码显示了我已经取得了多少成功,它确实在右边x坐标处为文档添加了一个圆圈.现在,我该用什么替换问号?
svg.on("mousemove", function() {
d3.select("path.line")
.style("stroke-width", "2.5px");
svg.append("svg:circle")
.attr("cx", Math.floor(event.offsetX-m[1]))
.attr("cy", ?)
.attr("r", "10")
.attr("fill", "red");
});
Run Code Online (Sandbox Code Playgroud)
met*_*ion 27
SVG提供了一个本机函数.getPointAtLength(),该函数返回路径的x和y值,无论你在它传递的长度是多少.
您需要遍历线的长度,直到找到相应的y位置.以下是你在D3中的表现:
var svg = d3.select("#line").append("svg")
var path =
svg.append("path")
.attr("d", "M0,168L28,95.99999999999997L56,192L84,71.99999999999997L112,120L140,192L168,240L196,168L224,48L252,24L280,192L308,120L336,24L364,168L392,95.99999999999997L420,168L448,95.99999999999997L476,192L504,71.99999999999997L532,120L560,192L588,216L616,168L644,48L672,24L700,192L728,120L756,24L784,192L812,71.99999999999997")
.attr("fill", "none")
.attr("stroke", "black");
var circle =
svg.append("circle")
.attr("cx", 100)
.attr("cy", 350)
.attr("r", 3)
.attr("fill", "red");
var pathEl = path.node();
var pathLength = pathEl.getTotalLength();
var BBox = pathEl.getBBox();
var scale = pathLength/BBox.width;
var offsetLeft = document.getElementById("line").offsetLeft;
var randomizeButton = d3.select("button");
svg.on("mousemove", function() {
var x = d3.event.pageX - offsetLeft;
var beginning = x, end = pathLength, target;
while (true) {
target = Math.floor((beginning + end) / 2);
pos = pathEl.getPointAtLength(target);
if ((target === end || target === beginning) && pos.x !== x) {
break;
}
if (pos.x > x) end = target;
else if (pos.x < x) beginning = target;
else break; //position found
}
circle
.attr("opacity", 1)
.attr("cx", x)
.attr("cy", pos.y);
});
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到一个演示:http://bl.ocks.org/3824661
| 归档时间: |
|
| 查看次数: |
18706 次 |
| 最近记录: |