Home » D3 入門教學

[D3]用 D3.js 畫出 SVG 基本圖形 - 文字 text

D3 中使用 text 標籤來輸出基本的文字是一件簡單的事,同時還能再搭配 path 及 textPath 標籤來進行路徑的設計哩。

檢視原始碼 JavaScript
1
2
3
4
5
6
7
$(function(){
	// 在 body 中插入一個 svg
	var svg = d3.select('body').append('svg');
 
	// 在 svg 中插入一個 text
	svg.append('text').attr('x', 10).attr('y', 20).style('fill', 'steelblue').style('font-size', '24px').style('font-weight', 'bold').text('男丁格爾\'s 脫殼玩');
});

設定文字內容的部份就如同我們在使用 jQuery 一樣,只要使用 .text() 並指定內容就可以輸出了。

d3-draw-svg-shape-text-1

如果要再搭配 path 的話,得再插入一個 textPath 標籤才行:

檢視原始碼 JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$(function(){
	// 在 body 中插入一個 svg
	var svg = d3.select('body').append('svg');
 
	// 先在 svg 中插入一個 path
	svg.append('path').attr({
		id: 'mypath',
		d: 'M50 100Q350 50 350 250Q250 50 50 250'
	}).style({
		fill: 'none',
		stroke: 'green',
		'stroke-width': 10
	});
 
	// 接著在 svg 中插入一個 text
	// 並在 text 中插入一個 textPath
	svg.append('text').attr({
		x: 10, 
		y: 20
	}).style({
		fill: 'red',
		'font-size': '42px'
	}).append('textPath').attr({
		'xlink:href': '#mypath'
	}).text('男丁格爾\'s 脫殼玩 http://abgne.tw');
});

比較特別的是,當我們產生一個新的路徑的同時,也指定一個 id 屬性給該路徑。接著將 textPath 的 xlink:href 屬性值設定為該 id,這樣就能套用該路徑來輸出內容了。

d3-draw-svg-shape-text-2

text 標籤的屬性及說明可以參考:SVG 基本圖形 - 文字 text

發表迴響