繁体   English   中英

路径上的textpath的开始和结束

[英]Start and end of textpath on path

在我的d3.js代码中,我创建了一个带有偏移量的文本路径。 如何获取path.getPointAtLength指定的文本路径的开始和结束位置?

由于你没有提供你的代码,我将使用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> 

要获取起点和终点,我们需要两个值:路径长度和文本长度:

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> 

暂无
暂无

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

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