<div id="app" style="max-width:680px;margin:0 auto">
<template>
<div>
<svg style="width: 100%">
<g id="timeScale"
:transform="`translate(${-translatex},28)`"
fill="none"
font-size="10"
font-family="sans-serif"
text-anchor="middle">
<path class="domain" stroke="currentColor" :d="`M10.5,0.5H${4890.5+moveWidth}`"></path>
<g class="tick"
:class="{ major: index % 12 == 0 }"
opacity="1"
:transform="`translate(${(1880 / count) * index + 20},0)`"
v-for="(item, index) in timeList"
:key="index"
ref="time">
<line stroke="currentColor" :y2="showText(index)? 9 : 6"></line>
<text fill="#000" y="14" dy="0.71em" v-if="showText(index)">
{{ item }}
</text>
</g>
</g>
</svg>
</div>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="http://cdn.staticfile.org/moment.js/2.24.0/moment.js"></script>
<script>
var vue = new Vue({
el: '#app',
data: {
timeList: [],
tick: 0,
moveWidth:0,
translatex: 0,
count:144
},
created() {
this.moveWidth = 1880 / this.count;
this.createData();
},
methods: {
showText(index) {
if (index >= this.tick && (index == this.tick//第一条刻度判断
||
(
index - this.tick > 2//第一条刻度和下一条刻度需要大于2,下一条刻度在显示文字和长度为9的刻度线,防止文字重叠
&& index % 12 == 0)
)
) return true;
return false
},
animate() {
var timer = setInterval(() => {
this.translatex += 1;
if (this.translatex >= this.moveWidth) {
this.translatex = this.moveWidth;
clearInterval(timer);
this.tick++;
//重新获取数据
this.createData();
}
}, 50)
},
createData() {
this.timeList.splice(0, this.timeList.length)
let endDate = new Date();
let splitTime = 5 * 60 * 1000;
let count = this.count + this.tick;
//转为时间戳
let endTime = endDate.getTime();
let mod = endTime % splitTime;
if (mod > 0) {
endTime = endTime - mod;
}
endTime += this.tick * splitTime;
while (count-- > 0) {
let d = new Date();
d.setTime(endTime - count * splitTime);
this.timeList.push(moment(d).format("HH:mm"));
}
this.moveWidth += 1880 / this.count
setTimeout(() => {
this.animate();
}, 1000);//移动坐标轴,这里改为30s获取一次数据,测试1s一次
}
}
})
</script>