在我的d3.js代码中,我创建了一个带有偏移量的文本路径。如何获取根据path.getPointAtLength指定的文本路径的开始和结束位置?
答案 0 :(得分:3)
由于您没有提供代码,我将使用Mike Bostock的this example,将文本锚设置为middle
,将偏移设置为50%
,就像您一样做的:
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
svg.append("path")
.attr("id", "curve")
.attr("d", "M100,200C200,100 300,0 400,100C500,200 600,300 700,200C800,100 900,100 900,100");
svg.append("text")
.attr("id", "curve-text")
.append("textPath")
.attr("text-anchor", "middle")
.attr("xlink:href", "#curve")
.attr("startOffset", "50%")
.text("We go up and down and up");
#curve-text {
font: 40px sans-serif;
}
#curve {
stroke: #999;
fill: none;
}
<script src="//d3js.org/d3.v4.min.js"></script>
要获得起点和终点,我们需要两个值:路径的长度和文本的长度:
var pathLength = d3.select("path").node().getTotalLength();
var textLength = d3.select("text").node().getComputedTextLength();
使用这两个值,我们可以轻松计算得分。这里,0.5
是偏移量:
var startPoint = d3.select("path").node().getPointAtLength(pathLength * .5 - textLength / 2);
var endPoint = d3.select("path").node().getPointAtLength(pathLength * .5 + textLength / 2);
这是一个带有两个圆圈(蓝色和红色)的演示,显示了这些点:
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500);
svg.append("path")
.attr("id", "curve")
.attr("d", "M100,200C200,100 300,0 400,100C500,200 600,300 700,200C800,100 900,100 900,100");
svg.append("text")
.attr("id", "curve-text")
.append("textPath")
.attr("text-anchor", "middle")
.attr("xlink:href", "#curve")
.attr("startOffset", "50%")
.text("We go up and down and up");
var pathLength = d3.select("path").node().getTotalLength();
var textLength = d3.select("text").node().getComputedTextLength();
var startPoint = d3.select("path").node().getPointAtLength(pathLength * .5 - textLength / 2);
svg.append("circle").attr("cx", startPoint.x).attr("cy", startPoint.y).attr("r", 10).attr("fill", "blue").attr("opacity", .6);
var endPoint = d3.select("path").node().getPointAtLength(pathLength * .5 + textLength / 2);
svg.append("circle").attr("cx", endPoint.x).attr("cy", endPoint.y).attr("r", 10).attr("fill", "red").attr("opacity", .6);
#curve-text {
font: 40px sans-serif;
}
#curve {
stroke: #999;
fill: none;
}
<script src="//d3js.org/d3.v4.min.js"></script>