<canvas id="myCanvas" ref="myCanvas" >
</canvas>
const flag = ref(false)
const rectWidth = ref(0)//矩形框的宽
const rectHeight = ref(0) //矩形框的高
const totalRect = reactive([]) //画的所有的矩形坐标长度数据存储在数组中
const downX = ref(0)//鼠标点击图片落下时的位置(X)
const downY = ref(0)//鼠标点击图片落下时的位置(Y)
const ctx = ref("")//dom节点
const delIndex = ref(null)//删除时选中的矩形框的index
const myCanvas = ref(null);
const canvas = myCanvas.value;
const atime = ref('');
// // 放下鼠标
const mousedown= (e)=>{
console.log("鼠标落下");
atime.value= new Date().getTime();
flag.value= true;
downX.value= e.offsetX; // 鼠标落下时的X
downY.value= e.offsetY; // 鼠标落下时的X
mousemove(e);
}
// // 移动鼠标
const mousemove=(e)=>{
if(flag.value){
//判断如果重右下往左上画,这种画法直接return
if(downX.value- e.offsetX> 0 || downY.value- e.offsetY> 0){
console.log("重右下往左上画");
return
}else{
console.log("重左上往右下画");
// //如果重左上往右下画,计算出鼠标移动的距离,也就是矩形框的宽和高
rectWidth.value= Math.abs(downX.value- e.offsetX)
rectHeight.value= Math.abs(downY.value- e.offsetY)
console.log("this.rectWidth", rectWidth.value);
console.log("this.rectHeight", rectHeight.value);
// //判断这个宽高的长度,如果小于10,直接return,因为鼠标移动距离过于短
// //防止点击页面时,会画成一个点,没有意义
if (rectWidth.value< 10 || rectHeight.value< 10) {
console.log("只是点击");
rectWidth.value= 0;
rectHeight.value= 0;
return;
}
clear(); //清空画布
redrawAll();
drawRect(
downX.value,
downY.value,
rectWidth.value,
rectHeight.value
);
}
}
}
const redrawAll= ()=>{
console.log("先画之前画过的图,保证画多个的时候看起来像前一个不消失");
if(totalRect.length> 0){
totalRect.forEach((e) => {
drawRect(e.beforex, e.beforey, e.rectW, e.rectH);
});
}
}
// //清除画布
const clear= ()=>{
const canvas= myCanvas.value;
let ctx= canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
const drawRect= (x:any,y:any,lineW:any,lineY:any)=>{
const canvas= myCanvas.value;
let ctx= canvas.getContext("2d");
// 开始绘制;
ctx.beginPath();
// //设置线条颜色,必须放在绘制之前
ctx.strokeStyle= "#850a1e";
console.log("44444444");
// 线宽设置,必须放在绘制之前
ctx.lineWidth= 2;
// strokeRect参数:(左上角x坐标,y:左上角y坐标,绘画矩形的宽度,绘画矩形的高度)
ctx.strokeRect(x, y, lineW, lineY);
console.log("66666666666666");
}
// //点击画布
const findRect= (e)=>{
if (rectTag.value) {
console.log("eeeeeeeeeee", e);
console.log("this.totalRect", this.totalRect);
//当点击画布的时候,计算有没有点再矩形框内、哪个矩形框内
totalRect.map((item, index) => {
if (
e.offsetX- item.beforex> item.rectW||
e.offsetX< item.beforex||
e.offsetY- item.beforey> item.rectH||
e.offsetY< item.beforey
){
return;
}else {
//找到之后,设置下标
delIndex.value= index;
console.log("this.delIndex", this.delIndex);
}
})
}
}
//点击删除按钮
del() {
this.dialogVisible= false;
//删除
this.ctx.clearRect(
this.totalRect[this.delIndex].beforex- 2,
this.totalRect[this.delIndex].beforey- 2,
this.totalRect[this.delIndex].rectW+ 4,
this.totalRect[this.delIndex].rectH+ 4
);
//删掉totalRect的数据,真正的项目中需要调用后台接口,删掉数据库中存储的数据
this.totalRect.splice(this.delIndex, 1);
//删掉之后,再画一次,刷新页面
this.redrawAll();
console.log(this.totalRect, "删除了没");
},
},