自动化监控Zabbix运维驿站系统运维专家

D3.js 数据可视化 JS 库快速入门 + Observabl

2019-06-04  本文已影响5人  MercuryWang

D3 VS jQuery

刚开始接触 D3,很容易会联想到 jQuery,因为他们在操作元素的语法很相似。网上有这样一个问题:What is the difference between D3 and jQuery?

回答:

粗译:

1. 这里先提示一个小的 error,也许将来你在开发中也会遇到:

c-error.png

-- Error: Access to XHTMLHttpRequest at 'file/...' from origin 'null' has been blocked by CORS policy. ......

这个问题的出现是因为直接从浏览器, 而 Chrome 不允许这样访问。

解决方案:本地部署 web

npm i http-server -g
http-server

启动成功会显示如下界面

terminal.png

2. 言归正传,开始第一讲 select(), append(), text()

新建 HTML 文件,引入 d3 库:

<script src="http://d3js.org/d3.v3.min.js"></script>

给个 p 标签

<p>
  This is a test
</p>

然后我们来使用 d3 的 select(), append(), text() 方法:

// 改变 p 元素的文本
d3.select('p').text('test a is this');

// 选中 body 元素追加一个 p 标签并添加文本
d3
  .select('body')
  .append('p')
  .text('this is the second one');

页面显示:

test a is this

this is the second one

3. 画布和常见几何图形

D3 的坐标轴是这样的,坐标轴原点在左上角

d3axes.png
// 新建画布,添加宽度高度,但是画布在网页中是透明的,只有检查元素时可以看到它的大小区域
// 使用 SVG 来作图
var canvas = d3
  .select('body')
  .append('svg')
  .attr('width', 500)
  .attr('height', 500);

// 画圆
var circle = canvas
  .append('circle')
  .attr('cx', 250)
  .attr('cy', 250)
  .attr('r', 50)
  .attr('fill', 'blue');

var circle = canvas
  .append('circle')
  .attr('cx', 250) // 圆心在 X 轴的坐标
  .attr('cy', 250) // 圆心在 Y 轴的坐标
  .attr('r', 5) // 半径
  .attr('fill', '#fff'); // 填充色,如果不写,默认黑色

// 矩形
var rect = canvas
  .append('rect')
  .attr('width', 70)
  .attr('height', 50)
  .attr('fill', 'pink');

// 线,以两个端点固定线的位置,分别是 x1, x2, y1, y2
var line = canvas
  .append('line')
  .attr('x1', 49)
  .attr('y1', 49)
  .attr('x2', 250)
  .attr('y2', 250)
  .attr('stroke', 'green') // 颜色
  .attr('stroke-width', 5); // 粗细
额,画了个啥? three.png

4. 如何进阶学习

Github 有中文 API 文档,这里只贴出目录供参考,详细信息请查看 API 文档
看到这个目录确实有点头痛,更何况每个模块又有分项列表,很多方法。我个人的学习路径是:

这里附上我的分类,仅供参考:

分类 模块
⭐️ 计算类 Arrays, Collections, Hierarchies, Polygons, Quadtrees, Random Numbers,
⭐️ 数据处理类 Dispatches, Delimiter-Separated Values, Fetch, Number Formates, Interpolators, Paths
⭐️ 时间处理类 Time Formates, Time Intervals, Timers
⭐️ DOM 操作类 Selections
⭐️ 动画类 Easings, Transitions
👑 颜色类 Color, Color Schemes,
👑 鼠标控制 Brushes, Dragging, Zooming
👑 地理类 Geographies
👑 比例调整类 Axes, Scales,
👑 图形类 Shapes, Voronoi Diagrams, Contours, Forces, Chords

5. 官方画廊

点开 官方画廊 的示例,发现下面的代码根本看不懂

Screen Shot 2019-06-06 at 10.06.12 AM.png

原来 Observable 是一个在线开发编辑 D3 的工具,它的语法同我们平时开发是有些差异的。快速了解 Observable -- 『干货|d3创始人又一力作:不仅能在线写D3.js,还能让你写的更出色 』

另附 Observable: The User Manual 用户使用手册

上一篇 下一篇

猜你喜欢

热点阅读