> 文章列表 > d3入门练习系列(三)绘制svg基本形状

d3入门练习系列(三)绘制svg基本形状

d3入门练习系列(三)绘制svg基本形状

基本形状

如果你对svg绘图比较熟悉,那么通过d3绘制svg格式的基本形状,如线段、折线、多边形、矩形等等,将非常简单。
如果你不熟悉svg绘图,也没关系。举个例子:如下代码表示一个圆心在(25, 75)半径为20的圆:

<circle cx="25" cy="75" r="20"/>

可以参考官方文档:基本形状。一分钟的功夫,你就大概了解。

废话不多,直接上代码。

const height = 400, width = 600
const g= d3.select(".view").append("svg").attr('viewBox', [0, 0, width, height])/* 清楚绘图区*/
const clear = () => {g.selectChild().remove()
}const draw = {/ 矩形 */rect () {clear()g.append('rect').attr('x', '10').attr('y', '10').attr('width', '100').attr('height', '100')},/ 圆 */circle () {clear()g.append('circle').attr('cx', '60').attr('cy', '60').attr('r', '50')},/ 椭圆 */ellipse () {clear()g.append('ellipse').attr('cx', '60').attr('cy', '60').attr('rx', '30').attr('ry', '10')},/ 线段 */line () {clear()g.append('line').attr('x1', '10').attr('y1', '10').attr('x2', '100').attr('y2', '100').attr('stroke', 'red').attr('stroke-width', '2')},/ 折线 */polyline () {clear()const points = [[0, 0],[10, 10],[50, 50],[50, 100],[00, 100],]const v = points.map((pt) => pt.join(',')).join(' ') // 逗号、空格分割都OKg.append('polyline').attr('points',v).attr('fill', 'none').attr('stroke', 'black').attr('stroke-width', '3')},/ 多边形 */polygon () {clear()const points = [[0, 0],[10, 10],[50, 50],[50, 100],[00, 100],]const v = points.map((pt) => pt.join(' ')).join(',')g.append('polygon').attr('points',v)}
}

基本上就是创建一个形状标签,然后通过attr方法将相应的属性及属性值加上去就OK。
基本形状对应的标有:

  • 矩形 - rect
  • 圆 - circle
  • 椭圆 - ellipse
  • 线条 - line
  • 折线 - polyline
  • 多边形 - polygon

path用法

path功能比较强大,可以绘制各种形状。
path元素的形状是通过属性 d 定义的。d的值是 命令 + 参数 的序列。

<path d="M 10 10"></path>

表示将画笔移动到(10, 10)点。
M即 move to,是移动画笔,并没有真正的画出来。
M后面的两个数字是命令参数, 代表x, y坐标。

还有其它命令如:

  • L x y, 在当前位置和xy位置上画一个线段
  • H x, 水平方向绘制线段
  • V y, 垂直方向绘制线段
  • Z ,闭合路径

每个命令可以是大写或者小写,大写采用绝对定位,小写采用相对定位。

L 20 30

表示在画笔位置和(20, 30)点之间画一个直线。

l 20 30

表示从画笔位置开始,向x轴正方向(向右)移动20,向y轴正方向(向下)移动30,在这个位置和画笔位置之间画一个线段。
注意:svg的坐标系统,原点在左上角。

利用path绘制线条、矩形

const path = {line () {clear()g.append('path').attr('d', 'M10 10 L 110 110') // 从(10,10)点开始,到(110, 110)点.attr('stroke', 'red')},rect () {clear()g.append('path').attr('d', 'M10 10 l 110 0 v 50 h -110 v -50') // 从(10,10)点开始,向右移动110,再向下移动50,再向左移动110,再向上50.attr('stroke', 'red').attr('fill', '#ccc')}
}

path绘制圆形、椭圆、弧线是通过弧线命令 A 来进行,A命令非常强大但也很复杂,一般很少用到,后面有需要可以在专门学习。

今天绘制基本形状,都是简单的将svg格式内容通过d3简单的创建出来。了解svg的基本基础和d3操作svg基本用法。