简体   繁体   English

路径上的textpath的开始和结束

[英]Start and end of textpath on path

In my d3.js code, I have created a textpath with some offset. 在我的d3.js代码中,我创建了一个带有偏移量的文本路径。 How can I get the start and end position of the textpath specified in terms of path.getPointAtLength? 如何获取path.getPointAtLength指定的文本路径的开始和结束位置?

Since you didn't provide your code, I'm going to use this example from Mike Bostock, setting the text-anchor to middle and the offset to 50% , as you did: 由于你没有提供你的代码,我将使用Mike Bostock的这个例子 ,将text-anchor设置为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> 

To get the start and end points, we need two values: the length of the path and the length of the text: 要获取起点和终点,我们需要两个值:路径长度和文本长度:

var pathLength = d3.select("path").node().getTotalLength();
var textLength = d3.select("text").node().getComputedTextLength();

With those two values we can easily calculate the points. 有了这两个值,我们就可以轻松计算出这些点。 Here, 0.5 is the offset: 这里, 0.5是偏移量:

var startPoint = d3.select("path").node().getPointAtLength(pathLength * .5 - textLength / 2);
var endPoint = d3.select("path").node().getPointAtLength(pathLength * .5 + textLength / 2);

Here is the demo with two circles (blue and red) showing the points: 这是一个带有两个圆圈(蓝色和红色)的演示,显示了这些点:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM