<template>
<div class="box">
<!--
canvas 画矩形
注意:
1. 首先要有三个鼠标事件,
2. 保存画好的矩形,只能用鼠标up的时候保存住坐标,然后每次move都循环显示它
3. (0,499,137,-126) 这样的坐标,问后台是否可以
-->
<div class="bg">
<!-- 在css设置了canvas本身的大小,在mountd里写的宽高 设置了canvas画布大小 -->
<canvas id="myCanvas" @mousedown='mousedown' @mousemove='mousemove' @mouseup='mouseup'></canvas>
</div>
</div>
</template>
<script>
export default {
data () {
return {
start_x:'',
start_y:'',
end_x:'',
end_y:'',
flag: false,
list:[]
}
},
mounted() {
this.$nextTick(()=>{
const canvas = document.getElementById('myCanvas')
this.ctx = canvas.getContext("2d");
const bg = document.getElementsByClassName('bg')[0] //动态获取父元素 宽高--->赋值
canvas.width = bg.clientWidth
canvas.height = bg.clientHeight
console.log(canvas.width,canvas.height,'00')
// (46,90,16,102)
})
},
methods:{
mousedown(event){
// 鼠标开始记录坐标
this.flag = true
this.start_x = event.offsetX
this.start_y = event.offsetY
console.log('开始点')
},
mousemove(event){
// 鼠标移动过程中画矩形框
// console.log(event.offsetX,event.offsetY,'移动中')
this.drawRect(event);
},
drawRect(event){
if(this.flag){
// console.log('移动中')
this.end_x = event.offsetX
this.end_y = event.offsetY
// 清除画布,相当于橡皮擦?
const canvas = document.getElementById('myCanvas')
this.ctx.clearRect(0,0,canvas.width,canvas.height);
// 绘制保存的坐标
this.list.forEach((value)=>{
this.ctx.strokeRect(value.start_x,value.start_y,value.width,value.height);
})
// 开始绘制
this.ctx.beginPath();
//设置线条颜色,必须放在绘制之前
this.ctx.strokeStyle = 'block';
// 线宽设置,必须放在绘制之前
this.ctx.lineWidth = 1;
// 进行矩形绘制(矩形左上角的 x 坐标,矩形左上角的 y 坐标,矩形的宽度,矩形的高度)
this.ctx.strokeRect(this.start_x,this.start_y,this.end_x-this.start_x,this.end_y-this.start_y);
}
},
mouseup(){
this.flag = false
// 停止保存坐标
this.list.push({
start_x: this.start_x,
start_y: this.start_y,
width: this.end_x - this.start_x,
height: this.end_y - this.start_y,
})
console.log(this.list,this.end_y,'结束')
}
}
}
</script>
<style scoped>
.box{
width: 100%;
height: 100%;
position: relative;
}
.bg{
width: 500px;
height: 500px;
position: absolute;
top: 0;
left: 50px;
background: url('../assets/123.png');
background-position: center;
background-size: cover;
/* z-index: 10; */
}
canvas{
/* z-index: 120; */
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
border: 1px solid red;
}
</style>
网友评论