JS中使用textPath實現(xiàn)線條上的文字
近期在項目中要實現(xiàn)關系圖,需要在線條上繪制文字。要實現(xiàn)這個功能,我們需要在SVG中連接的線條從標簽line修改為path,這樣才可能實現(xiàn)類似如下的效果:
1個簡單的例子如下所示:
<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>
在這里我們需要實現(xiàn)1個path,然后設置其ID屬性,之后我們創(chuàng)建textPath標簽,并鏈接到上述的ID屬性,這樣就可以實現(xià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;
})
實際上這段代碼就是上述例子的實現(xiàn),這樣就可以避免編寫繁瑣的SVG代碼了。
總結
以上所述是小編給大家介紹的使用textPath實現(xiàn)線條上的文字,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
關于window.pageYOffset和document.documentElement.scrollTop
window.pageYOffset:Netscape屬性,指的是滾動條頂部到網(wǎng)頁頂部的距離2011-04-04
JavaScript asp.net 獲取當前超鏈接中的文本
今天用到,不會。網(wǎng)上找到一個方法,趕快記下來。可以獲取超鏈接的鏈接文本。2009-04-04
javascript中setAttribute()函數(shù)使用方法及兼容性
這篇文章主要介紹了javascript中setAttribute()函數(shù)使用方法及兼容性的相關資料,需要的朋友可以參考下2015-07-07

