绘制时间轴?当然用SVG啦!

405 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情

1、首言

最近接到一个需求,需要用jQuery UI完成时间轴的拖拽维护。在实现功能的过程中,了解到了SVG,个人觉得项目中如果使用SVG,功能实现起来可能会更简单。以下便是个人用SVG实现时间轴的过程。首先,将页面分为两个部分,一部分为素材区,一部分为时间轴维护区。本篇文章主要讲素材的绘制以及拖动效果的实现。

2、素材区

首先我需要一个时间轴节点、一个文本编辑区域。

代码部分:

<div style="height: 300px;width: 100%;background-color: pink;">
        <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
            <circle cx="100" cy="50" r="5"  fill="blue" />
            <circle cx="100" cy="50" r="10" stroke="blue"  fill="none" />
            <foreignObject x="200" y="30" width="100" height="50" fill="green" style="background:blue;fill:green;border:1px solid #000;stroke:pink;stroke-width:5;opacity:0.5">
                <input type="text" style="width: 100px;height: 50px;" />
            </foreignObject>
         </svg> 
</div>

展示效果:

image.png

3、实现元素之间的连线

既然是时间轴,节点之间肯定需要线来连接。svg中提供了三种画线方式。

3.1 直线 <line>

功能单一,但基本符合需求。

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <line x1="10" y1="10" x2="100" y2="10" style="stroke:blue;stroke-width:2" />
</svg>

效果如下:

image.png

3.2 路径<path>

<path>是svg中较强大的基本形状,可以用来创建直线、曲线、弧形、多边形等图形。目前只用来画直线

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="400" width="450">
<path d="M 175 200 l 150 0" stroke="green" stroke-width="3" fill="none" />
</svg>

效果如下:

image.png

3.3 折线<polyline>

通过一系列坐标完成点与点的连线。可以绘制各种图案,用来绘制直线会更简单更容易理解

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="400" width="450">
	<polyline points="150,75 258,75"stroke="black" stroke-width="3" fill="none"></polyline>
</svg>

效果如下:

image.png

4、以上,绘制时间轴所需的基本元素都已就位,后续将会继续更新时间轴的绘制。