首页 > 代码库 > d3.js学习

d3.js学习

画svg图像

1.添加svg元素

2.添加g元素,g元素是一个分组的元素,相当于html中的div元素

3.画图像

4.画坐标轴

-----------------------------------------------------------------------------

d3画闲线性曲线例子

html:

  

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>d3.js</title>
<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/css/style.css">
</head>
<body>
<div id="container">

</div>
<script type="text/javascript" src="http://www.mamicode.com/js/d3.v3.js"></script>
<script type="text/javascript" src="http://www.mamicode.com/js/index.js"></script>

</body>
</html>

 

index.js :

var width = 500,
height = 250,
margin = {left:50,top:30,right:20,bottom:20},
g_width = width - margin.left - margin.right,
g_height = height - margin.top - margin.bottom;

//svg
var svg = d3.select("#container")//选择html中已经存在的元素并在这个元素里添加一个svg元素
.append("svg")
.attr("width",width)
.attr("height",height)

var g = d3.select("svg")
.append(‘g‘)
.attr("transform","translate(" + margin.left + "," + margin.top + ")")//偏移g元素

var data = http://www.mamicode.com/[1,3,5,7,8,4,3,7];
var scale_x = d3.scale.linear()//x轴的缩放函数,domain为输入范围,range为输出范围
.domain([0,data.length - 1])//input
.range([0,g_width])// out

var scale_y = d3.scale.linear()//x轴的缩放函数
.domain([0,d3.max(data)])//input  输入的范围
.range([g_height,0])//out输出范围

var line_generator = d3.svg.line()
.x(function(d,i){return scale_x(i);})// i 0 1 2 3 4 5 6 ...
.y(function(d,i){return scale_y(d);})//d 1 3 5 7 8 4 3 7
.interpolate("cardinal")//画曲线的函数

g
.append("path")
.attr("d",line_generator(data))//d 是path-data  的缩写

///
var x_axis = d3.svg.axis().scale(scale_x),//x坐标轴
y_axis = d3.svg.axis().scale(scale_y).orient("left");//y坐标轴

g.append("g")
.call(x_axis)
.attr("transform","translate(0," + g_height + ")")//画x轴坐标

g.append("g")
.call(y_axis)
.append("text")
.text("Price($)")
.attr("transform","rotate(-90)")
.attr("text-anchor","end")
.attr("dy","1em")//画y轴坐标并添加文字并对文字位置进行便宜翻转

 

 

style.css:

#container{
background:#ddd;
width: 500px;
height: 250px;
}

path{
fill: none;
stroke: #c03;
stroke-width:2;
}

.domain,.tick line{
stroke: #999;
stroke-width:1;
}

d3.js学习