简体   繁体   中英

Start and end of textpath on path

In my d3.js code, I have created a textpath with some offset. How can I get the start and end position of the textpath specified in terms of 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:

 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:

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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