需求:大概就是使用箭头进行标注需要指向的内容
上面是大致效果图
首先要创建一个canvas画布
<div style="flex: 5">
<canvas ref="canvasElement" @mousedown="startDrawing"
@mousemove="runDrawing" @mouseup="stopDrawing" @click="startContext">
</canvas>
</div>
其次,创建箭头图标符号
<el-button type="text" @click="checkGraph='arrow'" style="padding: 10px">
<div class="el-icon-top-left" style="font-size: 28px;color: black"></div>
<p style="color: black">箭头</p>
</el-button>
最后是关于js部分,从画笔开始的起始位置,到画笔结束的终点位置,完成箭头标注。
起始位置:
startDrawing(event) {
if (this.checkGraph === "arrow") {
this.startPoint.x = event.offsetX;
this.startPoint.y = event.offsetY;
this.painting = true;
}
},
鼠标事件的坐标确定箭头的起始点和结束点
runDrawing(event) {
this.graph[this.graphLength].lineWidth = this.canvasLineWidth;
this.graph[this.graphLength].color = this.canvasColor;
if (this.checkGraph === "arrow") {
if (this.painting) {
const mouseX = event.offsetX;
const mouseY = event.offsetY;
this.graph[this.graphLength].type = "arrow";
this.graph[this.graphLength].x = this.startPoint.x;
this.graph[this.graphLength].y = this.startPoint.y;
this.graph[this.graphLength].parse1 = mouseX;
this.graph[this.graphLength].parse2 = mouseY;
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.draw();
}
}
}
最终在画布上的效果
draw() {
this.ctx.putImageData(this.imageData, 0, 0);
this.graph.forEach(key => {
if (key.type === "arrow") {
this.ctx.lineWidth = key.lineWidth;
this.ctx.strokeStyle = key.color;
// 绘制箭头
this.ctx.beginPath();
this.ctx.moveTo(key.x, key.y);
this.ctx.lineTo(key.parse1, key.parse2);
this.ctx.stroke();
// 绘制箭头头部
const angle = Math.atan2(key.parse2 - key.y, key.parse1 - key.x);
this.ctx.beginPath();
this.ctx.moveTo(key.parse1, key.parse2);
this.ctx.lineTo(
key.parse1 - 10 * Math.cos(angle - Math.PI / 6),
key.parse2 - 10 * Math.sin(angle - Math.PI / 6)
);
this.ctx.lineTo(
key.parse1 - 10 * Math.cos(angle + Math.PI / 6),
key.parse2 - 10 * Math.sin(angle + Math.PI / 6)
);
this.ctx.closePath();
this.ctx.fillStyle = key.color; // 添加箭头头部颜色
this.ctx.fill();
}
})
this.ctx.lineWidth = this.canvasLineWidth;
this.ctx.color = this.canvasColor;
},
以上就是大致代码及流程。如果想要其他效果,可以自行添加。