为什么要学习D3.js啊?因为最近在看一本陈为等写的《数据可视化》书,看到书中所写的东西觉得很炫的同时,感觉可视化方法大有用处。另外,去年还听过袁晓如等人讲的《数据可视化技术前沿讲座》,一直就对可视化技术感兴趣,在加上最近在想一个如何从视觉的角度看待bit的问题,于是更对可视化有强烈的兴趣了。可视化的艺术化表现的一个案列就是,一个艺术家将pi=3.14.15926535。。。用一种巧妙的方法呈现出来,即通过给0到9标上不同的颜色并把将相同颜色的数字连起来的方法表现出了可视化的魅力,如下所示,我觉得这种方法可以增强人们对数字的感觉。另外,给自己一个有限的时间,尝试学习下新的技术。
可视化工具有很多,我选择了D3.js,推荐排名中为第一位,d3 is a general purpose visualization library。
开始动手干
- 我的操作系统是win7,首先安装好web服务器。百度知道“windows搭建web服务器”
http://jingyan.baidu.com/article/ed2a5d1f128ff609f6be17fa.html,在chrom浏览器中输入localhost,如果看到IIS7字样,就成功部署了web服务器了。 - 到网站:http://d3js.org/下载D3.zip,在C盘找到目录C:\inetpub\wwwroot,新建DDD目录,将D3.zip解压到C:\inetpub\wwwroot\DDD\d3目录下,可以看到三个文件
编写一个简单的Hello
world程序,保存为index.html,放到C:\inetpub\wwwroot\DDD目录下。在chrom浏览器中输入http://localhost/DDD/,可以看到Hello
world。 index.html内容如下:
在 chorme浏览器中更多工具栏找到开发者选项(或者按ctrl+shift+I)打开了chrome的DevTools
window,定位到element选项,可以看到纯html代码。从网址含有的大量例子中选择一个感兴趣的例子来实验。
http://www.open-open.com/lib/view/open1387100056093.html?&from=androidqq。
首先要明白D3的语法结构,通过找资料发现D3中最困难的部分是:
我选择第326例来学习。
代码:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
background: #192887;
}
.graticule {
fill: none;
stroke: #fff;
stroke-width: .5px;
}
.land {
fill: #007421;
}
.dot {
fill: #c7141a;
}
.ring {
fill: none;
stroke: #c7141a;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960,
height = 500;
var projection = d3.geo.mercator()
.center([113, -3])
.scale(1275)
.translate([width / 2, height / 2])
.clipExtent([[0, 0], [width, height]])
.precision(.1);
var path = d3.geo.path()
.projection(projection);
var graticule = d3.geo.graticule()
.step([5, 5]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("path")
.datum(graticule)
.attr("class", "graticule")
.attr("d", path);
svg.append("circle")
.attr("class", "dot")
.attr("transform", "translate(" + projection([100, -8]) + ")")
.attr("r", 8);
setInterval(function() {
svg.append("circle")
.attr("class", "ring")
.attr("transform", "translate(" + projection([100, -8]) + ")")
.attr("r", 6)
.style("stroke-width", 3)
.style("stroke", "red")
.transition()
.ease("linear")
.duration(6000)
.style("stroke-opacity", 1e-6)
.style("stroke-width", 1)
.style("stroke", "brown")
.attr("r", 160)
.remove();
}, 750);
</script>
效果如下:
相关知识
- html的语法
- css语法。CSS 规则由两个主要的部分构成:选择器,以及一条或多条声明。selector {declaration1; declaration2; … declarationN }。
- svg的文档语法结构
- XML语言的语法
- 工具,我这次用的是webstorm工具,但是要有activation code,比较麻烦,选择了试用。
- 算法,D3中充满各种算法,voronoi, quadtrees, convex hull, projections, circle fitting等。