当前位置:   article > 正文

视频回放时间轴_drawscaleline() // 绘制时间刻度

drawscaleline() // 绘制时间刻度

本文章将带你手摸手教学手写一个时间轴组件,小白也能学会的那种!!!

先看效果  https://live.csdn.net/v/277150

功能描述:拖拽时间轴 , 鼠标缩小放大刻度 ,  随播放的视频改变刻度时间等等

开发框架:vue2.x   (因为项目上用的vue2.x ,  当然其他框架微改一下就能用) 

要求:对canvas有基本的了解, 最好了解 , 便于代码理解  不了解也不影响, 本人开发这个项目前也只是听说过,并不了解  挂个canvas文档 Canvas - Web API 接口参考 | MDN

思路: 得有中间刻度不是?  得有时间刻度不是?  得有日期/时间不是? 得拖拽移动不是? 得有缩放功能不是? 得根据视频播放进度移动时间轴不是?  带着自己的目标一步一步实现 ,一开始想想的是利用dom操作实现时间轴功能,(固定宽度,循环刻度,显示隐藏方式切换实现缩放) 写了大概两天, 再添加移动时间后滚动效果很不丝滑,一度陷入了沉思... 终于后来找到一篇文档是利用canvas实现:手摸手带你实现一个时间轴组件 - 掘金

本文章基本思路是参考该文章,加了一些功能,也舍弃一些功能,看个人实际需求,话不多说直接开撸..

安装 moment 依赖 ( 项目中会用到该时间组件依赖 )

npm install  moment

vue页面引入  

 import moment from "moment";

vue页面html部分

  1. <template>
  2. <div class="timeLineContainer" ref="timeLineContainer">
  3. <canvas
  4. ref="canvas"
  5. @mousemove="onMousemove"
  6. @mousedown="onMousedown"
  7. @mousewheel="onMouseweel"
  8. @mouseup="onMouseup"
  9. @mouseout="onMouseout"
  10. ></canvas>
  11. </div>
  12. </template>

vue页面data数据

  1. data() {
  2. return {
  3. //时间分辨对应的层级
  4. currentZoomIndex: 0,
  5. // 中间刻度的当前时间 (默认为当天的0点减12小时,即昨天中午12点,若有操作时间则为操作后的时间)
  6. currentTime: new Date(moment().format("YYYY-MM-DD 00:00:00")).getTime(),
  7. // 时间轴左侧起点所代表的时间,默认为当天的0点减12小时,即昨天中午12点
  8. startTimestamp:
  9. new Date(moment().format("YYYY-MM-DD 00:00:00")).getTime() -
  10. 12 * ONE_HOUR_STAMP +
  11. 15 * 60 * 1000,
  12. width: null, //画布容器宽度
  13. height: null, //画布容器高度
  14. mousedown: false, // 移动开关
  15. ctx: null, //画布容器
  16. mousedownX: null, // 鼠标相当于时间轴左侧的距离
  17. //时间段数据
  18. timeSegments: [
  19. {
  20. beginTime: new Date("2023-02-18 02:30:00").getTime(),
  21. endTime: new Date("2023-02-18 11:20:00").getTime(),
  22. style: {
  23. background: "#5881CF",
  24. },
  25. },
  26. ],
  27. timer: null,//定时器
  28. };
  29. },

methods中初始化方法  获取到canvas容器注册好长宽  

温馨提示:调用init方法时,需要再dom注册之后  建议在this.$nextTick()中调用

  1. init() {
  2. // 获取外层宽高
  3. let { width, height } = this.$refs.timeLineContainer.getBoundingClientRect();
  4. this.width = width;
  5. this.height = height;
  6. // 设置画布宽高为外层元素宽高
  7. this.$refs.canvas.width = width;
  8. this.$refs.canvas.height = height;
  9. // 获取画图上下文
  10. this.ctx = this.$refs.canvas.getContext("2d");
  11. //绘制
  12. this.draw();
  13. },

draw方法

  1. draw() {
  2. this.drawScaleLine();//绘制时间刻度
  3. this.drawTimeSegments(); //绘制时间段
  4. this.drawMiddleLine();//绘制中线 绘制原则 想要谁的层级再最上面的随后绘制 前提是层级一样的时候
  5. },

首先先绘制出中线  执行drawMiddleLine方法   因频繁用到canvas的绘制划线  固将划线方法封装为

drawLine('起始x轴',起始"y轴",'内容x轴','内容y轴',"内容宽度","内容颜色") 参数目前只用到五个(自定义)

  1. // 画中间的白色竖线
  2. drawMiddleLine() {
  3. //中线的宽度
  4. let lineWidth = 2;
  5. // 线的x坐标是时间轴的中点,y坐标即时间轴的高度
  6. let x = this.width / 2;
  7. //划线
  8. this.drawLine(x, 0, x, this.height, lineWidth, "#fff");
  9. },

drawLine方法  尽量看懂  看不懂就当是划线的方法

  1. // 画线段方法
  2. drawLine(x1, y1, x2, y2, lineWidth, color) {
  3. // 开始一段新路径
  4. this.ctx.beginPath();
  5. // 设置线段颜色
  6. this.ctx.strokeStyle =color || "#fff";
  7. // 设置线段宽度
  8. this.ctx.lineWidth = lineWidth || 1;
  9. // 将路径起点移到x1,y1
  10. this.ctx.moveTo(x1, y1);
  11. // 将路径移动到x2,y2
  12. this.ctx.lineTo(x2, y2);
  13. // 把路径画出来
  14. this.ctx.stroke();
  15. },

到目前为止  就能再我们的容器最中间中看到一条白线(颜色可自定义) 如下图所示

 当然距离最终目的还差了十万八千里,但至少到现在能确保代码不报错 说明你已经成功了百分之***

继续明确目的  绘制刻度  绘制时间  具有事件交互才算完 

定义两个全局变量控制缩放及计算

  1. // 一小时的毫秒数
  2. const ONE_HOUR_STAMP = 60 * 60 * 1000;
  3. // 时间分辨率
  4. const ZOOM = [0.5, 1, 2, 6, 12, 24];

最重要的部分来了,本段代码建议将所有业务全部完后反复阅读理解 , 先看代码再说

  1. //画刻度
  2. drawScaleLine() {
  3. // 时间分辨率对应的每格小时数
  4. const ZOOM_HOUR_GRID = [1 / 60, 1 / 60, 2 / 60, 1 / 6, 0.25, 0.5];
  5. // 一共可以绘制的格数,时间轴的时间范围小时数除以每格代表的小时数,24/0.5=48
  6. let gridNum =
  7. ZOOM[this.currentZoomIndex] / ZOOM_HOUR_GRID[this.currentZoomIndex];
  8. // 一格多少毫秒,将每格代表的小时数转成毫秒数就可以了 ;
  9. let msPerGrid = ZOOM_HOUR_GRID[this.currentZoomIndex] * ONE_HOUR_STAMP;
  10. // 每格宽度,时间轴的宽度除以总格数
  11. let pxPerGrid = this.width / gridNum;
  12. // 时间偏移量,初始时间除每格时间取余数,
  13. let msOffset = msPerGrid - (this.startTimestamp % msPerGrid);
  14. // 距离偏移量,时间偏移量和每格时间比例乘每格像素
  15. let pxOffset = (msOffset / msPerGrid) * pxPerGrid;
  16. // 时间分辨率对应的时间显示判断条件
  17. const ZOOM_DATE_SHOW_RULE = [
  18. () => {
  19. // 全都显示
  20. return true;
  21. },
  22. (date) => {
  23. // 每五分钟显示
  24. return date.getMinutes() % 5 === 0;
  25. },
  26. (date) => {
  27. // 显示10、20、30...分钟数
  28. return date.getMinutes() % 10 === 0;
  29. },
  30. (date) => {
  31. // 显示整点和半点小时
  32. return date.getMinutes() === 0 || date.getMinutes() === 30;
  33. },
  34. (date) => {
  35. // 显示整点小时
  36. return date.getMinutes() === 0;
  37. },
  38. (date) => {
  39. // 显示2、4、6...整点小时
  40. return date.getHours() % 2 === 0 && date.getMinutes() === 0;
  41. },
  42. ];
  43. for (let i = 0; i < gridNum; i++) {
  44. // 横坐标就是当前索引乘每格宽度
  45. let x = pxOffset + i * pxPerGrid;
  46. // 当前刻度的时间,时间轴起始时间加上当前格子数乘每格代表的毫秒数
  47. let graduationTime = this.startTimestamp + msOffset + i * msPerGrid;
  48. // 时间刻度高度 根据刻/时/月展示高度不同 具体可以自己去定义
  49. let h = 0;
  50. let date = new Date(graduationTime);
  51. if (date.getHours() === 0 && date.getMinutes() === 0) {
  52. // 其他根据判断条件来显示
  53. h = this.height * 0.3;
  54. // 刻度线颜色
  55. this.ctx.fillStyle = "rgba(151,158,167,1)";
  56. // 显示时间
  57. this.ctx.fillText(
  58. this.graduationTitle(graduationTime),
  59. x - 13,// 向左平移一半
  60. h + 15 // 加上行高
  61. );
  62. } else if (ZOOM_DATE_SHOW_RULE[this.currentZoomIndex](date)) {
  63. h = this.height * 0.2;
  64. this.ctx.fillStyle = "rgba(151,158,167,1)";
  65. this.ctx.fillText(
  66. this.graduationTitle(graduationTime),
  67. x - 13,
  68. h + 15
  69. );
  70. } else {
  71. // 其他不显示时间
  72. h = this.height * 0.15;
  73. }
  74. this.drawLine(x, 0, x, h, 1, "#fff");
  75. }
  76. },

其中用到一个graduationTitle方法其作用是用于再0点时候显示的是日期  方法内容如下

  1. //格式时间的,在0点时显示日期而不是时间
  2. graduationTitle(datetime) {
  3. let time = moment(datetime);
  4. // 0点则显示当天日期
  5. if (
  6. time.hours() === 0 &&
  7. time.minutes() === 0 &&
  8. time.milliseconds() === 0
  9. ) {
  10. return time.format("MM-DD");
  11. } else {
  12. // 否则显示小时和分钟
  13. return time.format("HH:mm");
  14. }
  15. },

现在我们就能再页面上清除的看到我们的刻度了,,但是刻度存在并无实质性交互,

按照思路执行  鼠标点击拖拽时候实现滚动   移动展示时间  鼠标离开拖拽时候获取到中线时间用于通知回放视频应该回放的时间点 . 说干就干

首先记录鼠标点击下时候的时间 onMousedown方法

  1. //鼠标按下的操作
  2. onMousedown(e) {
  3. let { left } = this.$refs.canvas.getBoundingClientRect();
  4. // 也是计算鼠标相当于时间轴左侧的距离
  5. this.mousedownX = e.clientX - left;
  6. // 设置一下标志位
  7. this.mousedown = true;
  8. // 缓存一下鼠标按下时的起始时间点
  9. this.mousedownCacheStartTimestamp = this.startTimestamp;
  10. },

移动事件 onMousemove  分点击移动跟非点击移动  点击移动为拖拽  非点击移动为平移

  1. // 鼠标移动事件
  2. onMousemove(e) {
  3. // 计算出相对画布的位置
  4. let { left } = this.$refs.canvas.getBoundingClientRect();
  5. let x = e.clientX - left;
  6. // 计算出时间轴上每毫秒多少像素
  7. const PX_PER_MS =
  8. this.width / (ZOOM[this.currentZoomIndex] * ONE_HOUR_STAMP); // px/ms
  9. //拖拽时候
  10. if (this.mousedown) {
  11. // 计算鼠标当前相当于鼠标按下那个点的距离
  12. let diffX = x - this.mousedownX;
  13. // 用鼠标按下时的起始时间点减去拖动过程中的偏移量,往左拖是负值,减减得正,时间就是在增加,往右拖时间就是在减少
  14. this.startTimestamp =
  15. this.mousedownCacheStartTimestamp - Math.round(diffX / PX_PER_MS);
  16. // 不断刷新重绘就ok了
  17. this.ctx.clearRect(0, 0, this.width, this.height);
  18. this.draw();
  19. } else {
  20. // 计算所在位置的时间 平移时候
  21. let time = this.startTimestamp + x / PX_PER_MS;
  22. // 清除画布
  23. this.ctx.clearRect(0, 0, this.width, this.height);
  24. this.draw();
  25. // 绘制实时的竖线及时间
  26. this.drawLine(x, 0, x, this.height * 0.3, "#fff", 1);
  27. this.ctx.fillStyle = "#fff";
  28. this.ctx.fillText(
  29. moment(time).format("YYYY-MM-DD HH:mm:ss"),
  30. x - 20,
  31. this.height * 0.3 + 20
  32. );
  33. }
  34. },

鼠标松开时候  触发获取中间刻度的时间 onMouseup  得到的是时间戳存到 currentTime中

  1. //鼠标起来的操作
  2. onMouseup() {
  3. // 设置一下标志位 移动取消
  4. this.mousedown = false;
  5. //中间刻度距离左侧画布左侧距离
  6. let x = this.width / 2;
  7. // 计算出时间轴上每毫秒多少像素
  8. const PX_PER_MS =
  9. this.width / (ZOOM[this.currentZoomIndex] * ONE_HOUR_STAMP); // px/ms
  10. // 计算中间位置刻度的时间位置的时间
  11. this.currentTime = this.startTimestamp + x / PX_PER_MS;
  12. },

鼠标移出容器时候清除平移的日期时间 onMouseout事件

  1. //鼠标移出事件
  2. onMouseout() {
  3. // 清除画布
  4. this.ctx.clearRect(0, 0, this.width, this.height);
  5. //重新绘制画布
  6. this.draw();
  7. },

到目前位置时间轴基本功能大致已经差不多完成 看下效果

 之前有说到鼠标滚轮滚动时候能缩放时间刻度效果  onMouseweel事件  事件中的currentTime一定要为正线的时间刻度,否者再缩放时候 时间刻度会变动 (第一点再初始化时候给currentTime一个值,第二点在拖拽后计算出中线刻度时间)

  1. //鼠标滚动事件
  2. onMouseweel(event) {
  3. let e = window.event || event;
  4. let delta = Math.max(-1, Math.min(1, e.wheelDelta || -e.detail));
  5. if (delta < 0) {
  6. // 缩小
  7. if (this.currentZoomIndex + 1 >= ZOOM.length - 1) {
  8. this.currentZoomIndex = ZOOM.length - 1;
  9. } else {
  10. this.currentZoomIndex++;
  11. }
  12. } else if (delta > 0) {
  13. // 放大
  14. if (this.currentZoomIndex - 1 <= 0) {
  15. this.currentZoomIndex = 0;
  16. } else {
  17. this.currentZoomIndex--;
  18. }
  19. }
  20. this.ctx.clearRect(0, 0, this.width, this.height);
  21. // 重新计算起始时间点,当前时间-新的时间范围的一半
  22. this.startTimestamp =
  23. this.currentTime - (ZOOM[this.currentZoomIndex] * ONE_HOUR_STAMP) / 2;
  24. this.draw();
  25. },

展示图:省略  自行测试  用鼠标滚动可以缩放改变时间刻度即可

想想最后只剩下时间轴自己移动(定时器)  具体业务根据实际情况  我这里是拿到中间播放时间去请求回放视频流,再视频播放后有一个play回调,再回调中直接执行  在暂停 pause 回调中清除定时器

play()与pause()要根据每个人播放器不同而定  

  1. //播放
  2. play(){
  3. this.timer = setInterval(() => {
  4. //项目中我设置的是1秒钟移动一下刻度,结合实际情况分析 需要考虑跟播放速度 我本地项目不涉及到播放速度暂未考虑
  5. this.startTimestamp += 1000;
  6. //记录中间位置刻度 否者滚动之后中间刻度位置丢失
  7. this.onMouseup()
  8. // 不断刷新重绘就ok了
  9. this.ctx.clearRect(0, 0, this.width, this.height);
  10. this.draw();
  11. }, 1000);
  12. }
  13. //暂停
  14. pause(){
  15. clearInterval(this.timer);
  16. }

一定再页面销毁时候清除定时器

  1. beforeDestroy() {
  2. clearInterval(this.timer);
  3. },

大功告成了~~~

拓展在canvas中展示一个自定义时间段(直白点说我要展示2023年2月20一整天到时间轴中标记出来)  

在draw方法中调用一个drawTimeSegments方法    方法中的timeSegments对象有格式要求  可以参考data中timeSegments的格式  颜色/样式都可以自定义  

距离timeSegments参数:

  1. timeSegments: [
  2. {
  3. beginTime: new Date("2023-02-20 00:00:00").getTime(),
  4. endTime: new Date("2023-02-20 23:59:59").getTime(),
  5. style: {
  6. background: "#ffff00",
  7. },
  8. },
  9. ],
  1. //绘制时间段 开始到结束时都在
  2. drawTimeSegments() {
  3. const PX_PER_MS =
  4. this.width / (ZOOM[this.currentZoomIndex] * ONE_HOUR_STAMP); // px/ms
  5. this.timeSegments.forEach((item) => {
  6. if (
  7. item.beginTime <=
  8. this.startTimestamp +
  9. ZOOM[this.currentZoomIndex] * ONE_HOUR_STAMP &&
  10. item.endTime >= this.startTimestamp
  11. ) {
  12. let x = (item.beginTime - this.startTimestamp) * PX_PER_MS;
  13. let w;
  14. if (x < 0) {
  15. x = 0;
  16. w = (item.endTime - this.startTimestamp) * PX_PER_MS;
  17. } else {
  18. w = (item.endTime - item.beginTime) * PX_PER_MS;
  19. }
  20. this.ctx.fillStyle = item.style.background;
  21. this.ctx.fillRect(x, this.height * 0.6, w, this.height * 0.3);
  22. }
  23. });
  24. },

 终于结束了.....  如有不足请留言斧正  

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/230509
推荐阅读
相关标签
  

闽ICP备14008679号