Home » D3 入門教學

[D3]用 D3.js 畫出 SVG 基本圖形 - 直線 line

直線的部份也是能在 D3 中透過插入 line 標籤達成效果。

檢視原始碼 JavaScript
1
2
3
4
5
6
7
$(function(){
	// 在 body 中插入一個 svg
	var svg = d3.select('body').append('svg');
 
	// 在 svg 中插入一個 line
	svg.append('line').attr('x1', 40).attr('y1', 10).attr('x2', 200).attr('y2', 70).style('stroke', 'red').style('stroke-width', 5);
});

d3-draw-svg-shape-line-1

接著讓我們多插入幾條直線及圓形來產生井字遊戲的畫面:

檢視原始碼 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
$(function() {
	// 在 body 中插入一個 svg
	var svg = d3.select('body').append('svg');
 
	// 在 svg 中插入 line
	svg.append('line').attr({
		x1: 40,
		y1: 70,
		x2: 250,
		y2: 70
	}).style({
		stroke: 'black',
		'stroke-width': 5
	});
 
	// 在 svg 中插入 line
	svg.append('line').attr({
		x1: 40,
		y1: 140,
		x2: 250,
		y2: 140
	}).style({
		stroke: 'black',
		'stroke-width': 5
	});
 
	// 在 svg 中插入 line
	svg.append('line').attr({
		x1: 100,
		y1: 10,
		x2: 100,
		y2: 200
	}).style({
		stroke: 'black',
		'stroke-width': 5
	});
 
	// 在 svg 中插入 line
	svg.append('line').attr({
		x1: 180,
		y1: 10,
		x2: 180,
		y2: 200
	}).style({
		stroke: 'black',
		'stroke-width': 5
	});
 
	// 在 svg 中插入 circle
	svg.append('circle').attr({
		cx: 140,
		cy: 105,
		r: 20
	}).style({
		fill: 'none',
		stroke: 'red',
		'stroke-width': 4
	});
 
	// 在 svg 中插入 line
	svg.append('line').attr({
		x1: 50,
		y1: 20,
		x2: 80,
		y2: 50
	}).style({
		stroke: 'black',
		'stroke-width': 5
	});
 
	// 在 svg 中插入 line
	svg.append('line').attr({
		x1: 80,
		y1: 20,
		x2: 50,
		y2: 50
	}).style({
		stroke: 'black',
		'stroke-width': 5
	});
 
	// 在 svg 中插入 circle
	svg.append('circle').attr({
		cx: 220,
		cy: 180,
		r: 20
	}).style({
		fill: 'none',
		stroke: 'red',
		'stroke-width': 4
	});
});

d3-draw-svg-shape-line-2

line 標籤的屬性及說明可以參考:SVG 基本圖形 - 直線 line

發表迴響