下述点位可以通过websocket实时推送真实的points;我的箭头是用黑色三角形代替的(可自定义)
<template>
<div>
<canvas ref="canvas" width="800" height="600"></canvas>
</div>
</template>
<script>
export default {
mounted() {
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext("2d");
const points = [];
for (let i = 0; i < 10; i++) {
const x = Math.random() * this.canvas.width;
const y = Math.random() * this.canvas.height;
points.push({ x, y });
}
points.sort((a, b) => a.x - b.x);
this.draw(points);
},
methods: {
draw(points) {
const ctx = this.ctx;
const arrowInterval = 50; // 箭头间隔距离
ctx.lineWidth = 15; // 设置线段宽度为15px
ctx.strokeStyle = "green"; // 设置线段颜色为绿色
// 绘制线段
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.stroke();
// 绘制箭头
ctx.fillStyle = "black"; // 设置箭头颜色为黑色
let totalDistance = 0; // 累计距离
for (let i = 1; i < points.length; i++) {
const dx = points[i].x - points[i - 1].x;
const dy = points[i].y - points[i - 1].y;
const segmentDistance = Math.sqrt(dx * dx + dy * dy);
totalDistance += segmentDistance;
while (totalDistance >= arrowInterval) {
const ratio = (totalDistance - arrowInterval) / segmentDistance;
const arrowX = points[i - 1].x + dx * ratio;
const arrowY = points[i - 1].y + dy * ratio;
ctx.save();
ctx.translate(arrowX, arrowY);
ctx.rotate(Math.atan2(dy, dx));
ctx.beginPath();
ctx.moveTo(0, -5);
ctx.lineTo(10, 0);
ctx.lineTo(0, 5);
ctx.closePath();
ctx.fill();
ctx.restore();
totalDistance -= arrowInterval;
}
}
}
},
};
</script>
<style>
canvas {
border: 1px solid #000;
}
</style>
上图: