This article mainly shares with you a tutorial on how to use textPath to implement text on lines in JS. In recent projects, to implement relationship diagrams, text needs to be drawn on lines. To implement this function, we need to change the connected lines in SVG from the label line to path, so that it is possible to achieve an effect similar to the following:
1 Simple The example is as follows:
<svg viewBox="0 0 1000 300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <path id="MyPath" d="M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100" fill="none" stroke="red"/> <text font-family="Verdana" font-size="42.5"> <textPath xlink:href="#MyPath" rel="external nofollow" > We go up, then we go down, then up again </textPath> </text> </svg>
Here we need to implement a path, and then set its ID attribute. After that, we create the textPath tag and link to the above ID attribute, so that we can achieve association on the path. Text.
In D3 we can do this:
var link = svg.append("g").selectAll(".edgepath") .data(graph.links) .enter() .append("path") .style("stroke-width",0.5) .style("fill","none") .attr("marker-end",function(d){ return "url(#"+d.source+")"; }) .style("stroke","black") .attr("id", function(d,i){ return "edgepath"+i; }); var edges_text = svg.append("g").selectAll(".edgelabel") .data(graph.nodes) .enter() .append("text") .attr("class","edgelabel") .attr("id", function(d,i){ return "edgepath"+i; }) .attr("dx",80) .attr("dy",0); edges_text.append("textPath") .attr("xlink:href", function(d,i){ return "#edgepath"+i; }).text(function(d){ return d.id; })
In fact, this code is the implementation of the above example, so that you can avoid writing tedious SVG code.
Related recommendations:
SVG Basics|SVG TEXTPATH element
##SVG (scalable vector graphics) dashed line related attributes and Principle of line animation: a moving line
jQuery method to implement scrolling line navigation effect_jquery
The above is the detailed content of Tutorial on how to use textPath to implement text on lines in JS. For more information, please follow other related articles on the PHP Chinese website!