参考文档:手摸手带你实现一个时间轴组件
说明:实现思路来源于上面的文档,在此基础上做了一些调整,以符合项目需求
完成代码在github上,大家可以自行下载,喜欢的麻烦点个赞
另外也可以去npm直接下载插件
- 下载插件
yarn add v-time-shaft
- 全局引入
import TimerShaft from 'v-time-shaft' ...... Vue.use(TimerShaft)
- 组件中使用
<template> <div id="app"> <div class="timer-shaft-content"> <!-- 不限制时间范围,只初始化默认展示哪天的时间 --> <v-time-shaft date="2024-05-29"></v-time-shaft> </div> <div class="timer-shaft-content"> <!-- 限制时间范围的有用法 --> <v-time-shaft isLimit :date="date" :dateRange="dateRange"></v-time-shaft> </div> </div> </template>
效果图:
- 成品效果图
- 放大后,查看时间片段
- 不限制范围拖动到前一天
- 时间指示器【鼠标移入,产生的蓝色线条和时间点】
开发环境
node v16.18.0
yarn v1.22.19
vue 模版
事件绑定在canvas的容器上,方便进行canvas分层绘制
<template>
<div
class="canvas-contain"
ref="canvasContain"
@mousedown="onMousedown"
@mouseup="onMouseup"
@mouseout="onMouseout"
@mousemove="onMousemove"
@mousewheel="onMousewheel"
>
<canvas ref="canvas"></canvas>
<canvas class="canvas-line" ref="canvasLine"></canvas>
</div>
</template>
<style lang="less" scoped>
.canvas-contain {
width: 100%;
height: 100%;
position: relative;
.canvas-line {
position: absolute;
left: 0;
top: 0;
}
}
</style>
- 一个canvas用于绘制时间轴,一个处理鼠标移动绘制时间指示器
- 模版和样式表都非常简单,不做赘述
实现步骤
实现逻辑:在一个缩放等级下,确定用多少根刻度线画出所有对应的时间范围
如:缩放等级下24小时的时间轴,则要在canvas范围内绘制多根刻度线表示24小时
开始开发
初始化
- 创建一个init方法
- 设置浏览器变化的resize事件
this.init();
window.addEventListener('resize', this.init)
- 设置一下画布的宽高及获取画布上下文:
init() {
this.contain = this.$refs.canvasContain
if (!this.contain) return
this.canvas = this.$refs.canvas
this.canvasLine = this.$refs.canvasLine
let {
width, height} = this.contain.getBoundingClientRect()
// 缓存width,height
Object.assign(this, {
width, height})
// 设置canvas width,height
Object.assign(this.canvas, {
width, height})
Object.assign(this.canvasLine, {
width, height})
// 获取画布上下文
this.ctx = this.canvas.getContext('2d')
this.ctxLine = this.canvasLine.getContext('2d')
// 开始绘制
this.draw()
},
可传参数说明:
timeSegmentsData
- Array[object] 时间范围片段数据,
// 基本结构如下:
[{
id,
beginTime, // 片段开始时间,时间戳,单位毫秒
finishTime, // 片段结束时间,时间戳,单位毫秒
active, // 是否选中状态
lineWidth, // 片段边框的线宽
y, // 片段在canvas上距离顶部距离
h, // 片段在canvas上的高度
bgColor, // 片段背景颜色
borderColor, // 片段边框颜色
bgColorActive, // 片段选中状态背景颜色
borderColorActive, // 片段选中状态边框颜色
...
}]
gridStyles
- Object 时间刻度样式
// 支持属性:
{
lineColor, // 刻度线条颜色
lineWidth, // 刻度线条宽度
lineHeight // 刻度线条高度
color, // 刻度上时间的文字颜色
dateColor, // 刻度上的日期文字颜色
bgColor, // 刻度条背景颜色
bgHeight,