概述:点击右边图例=》点击画布进行绘制+》点击一键连线。
----------前期工作创建canvas实例
<template>
<canvas class="rt_rt_center" :width="canvasWith" :height="canvasHeight" ref="can" @click="canVas"></canvas>
<template/>
mounted(){
this.canvas = this.$refs.can;
this.ctx = this.canvas.getContext("2d");
}
第一步:点击画布进行绘制
methods:{
//点击画布时
canvas(){
//获取点击的坐标
var baseX = event.clientX - rect.left;
var baseY = event.clientY - rect.top;
//把点击的坐标存到数组以便于之后的连线
this.branchk.push({ baseX: baseX, baseY: baseY })
//调用画圆的方法,count需自己定义,他是你想写入圆内的文本
this.drawPoint(baseX, baseY,count);
},
//绘制圆的方法x和y是坐标,coun是圆上的文本
drawPoint(x, y, coun) {
this.ctx.beginPath();
this.ctx.arc(x, y, 20, 0, 2 * Math.PI);
// 圆
this.ctx.font = "30px Arial";
this.ctx.fillStyle = "#000000";
this.ctx.fill();
this.ctx.closePath();
// 填充圆内文本
this.ctx.font = "20px Arial";
this.ctx.fillStyle = "#fff";
this.ctx.textAlign = "center";
this.ctx.fillText(coun, x, y + 5);
},
}
第二步:自己设置一个按钮调用这个方法drawLins,里面参数是上面的this.branck数组,进行连线
methods:{
//点击一键连线,first是之前存储的两种圆的数组,第二步中的heBing数组,点击调用此方法直接进行连线
drawLins: function (first) {
for (var i = 0; i < first.length - 1; i++) {
const { baseX: startX, baseY: startY } = first[i];
const { baseX: endX, baseY: endY } = first[i + 1];
this.ctx.beginPath();
this.ctx.moveTo(startX, startY);
this.ctx.lineTo(endX, endY);
this.ctx.strokeStyle = this.lineColors;
this.ctx.stroke();
this.ctx.closePath();
}
},
}
注:可能有的括号符号不全,请注意检查,