近期在項(xiàng)目中要實(shí)現(xiàn)關(guān)系圖,需要在線條上繪制文字。要實(shí)現(xiàn)這個(gè)功能,我們需要在SVG中連接的線條從標(biāo)簽line修改為path,這樣才可能實(shí)現(xiàn)類似如下的效果:
1個(gè)簡單的例子如下所示:
<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>
在這里我們需要實(shí)現(xiàn)1個(gè)path,然后設(shè)置其ID屬性,之后我們創(chuàng)建textPath標(biāo)簽,并鏈接到上述的ID屬性,這樣就可以實(shí)現(xiàn)在路徑上關(guān)聯(lián)文字了。
而在D3中我們可以這樣操作:
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; })
實(shí)際上這段代碼就是上述例子的實(shí)現(xiàn),這樣就可以避免編寫繁瑣的SVG代碼了。
總結(jié)
以上所述是小編給大家介紹的使用textPath實(shí)現(xiàn)線條上的文字,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com