d3.js--01

D3 的全称是(Data-Driven Documents),顾名思义可以知道是一个被数据驱动的文档。听名字有点抽象,说简单一点,其实就是一个 JavaScript 的函数库,使用它主要是用来做数据可视化的。

使用:直接引用即可使用。

demo1:

  使用d3来修改hello world

 1 <html> 
 2   <head> 
 3         <meta charset="utf-8"> 
 4         <title>HelloWorld</title> 
 5   </head> 
 6     <body> 
 7         <p>Hello World 1</p>
 8         <p>Hello World 2</p>
 9         <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> 
10         <script>  
11         d3.select("body").selectAll("p").text("www.decembercafe.org");      
12         </script> 
13     </body> 
14 </html>
1 //选择<body>中所有的<p>,其文本内容为 www.ourd3js.com,选择集保存在变量 p 中
2 var p = d3.select("body")
3           .selectAll("p")
4           .text("www.ourd3js.com");
5 
6 //修改段落的颜色和字体大小
7 p.style("color","red")
8  .style("font-size","72px");

选择集

使用 d3.select() 或 d3.selectAll() 选择元素后返回的对象,就是选择集

区别:select()只返回第一元素对象

   selectAll()返回所有元素的对象

demo2:

  圆形和矩形

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>first</title>
 6     <style>
 7         .mycircle{
 8             fill:blue;
 9             stroke:green;
10             stroke-width:3px;
11         }
12         .myrect{
13             fill: red;
14             stroke:green;
15             stroke-width: 6px;
16         }
17 
18     </style>
19    
20 </head>
21 <body>
22     <script src="d3.js"></script>
23     <script>
24     //动态插入html
25     var body = d3.select('body');
26     body.append('h1')
27         .text('hello world');
28 
29     body.append('p')
30         .text('d3 d3');
31     //创建svg
32     var svg = body.append('svg')
33                   .attr('width',400)
34                   .attr('height',400);
35     svg.append('circle')
36         .attr('cx',100)
37         .attr('cy',200)
38         .attr('r',80)
39         .attr('class','mycircle');
40 
41     svg.append('rect')
42        .attr('x',200)
43        .attr('y',0)
44        .attr('width',150)
45        .attr('height',200)
46        .attr('class','myrect');
47 
48      </script>
49 
50 
51 </body>
52 </html>

备注:svg矢量图

  • 矩形 <rect>
  • 圆形 <circle>
  • 椭圆 <ellipse>
  • 线 <line>
  • 折线 <polyline>
  • 多边形 <polygon>
  • 路径 <path>

圆:circle  cx:x轴坐标   cy:y轴坐标  r :半径

矩形:rect   x:x轴坐标   y:y轴坐标

fill:填充属性

stroke:描边属性

stroke-width:描边宽度

原文地址:https://www.cnblogs.com/thelongmarch/p/6626546.html