使用canvas实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas绘制矩形</title>
<style>
#processboard{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#myCanvas{
background-color: #8db4ff;
}
#btnContainer{
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div id="processboard" class="flex-column">
<div>
<canvas id="myCanvas" ref="myCanvas" width="510" height="300" :style="{'background-image': 'url(' + currentCameraUrl + ')'}"
@mousedown="mousedown" @mouseup="mouseup" @mousemove="mousemove">
</canvas>
</div>
<div id="btnContainer">
<el-button @click="start">开始</el-button>
<el-button @click="save" type="primary">保存</el-button>
<el-button @click="clearArea" type="danger">清除</el-button>
</div>
</div>
<!-- 引入vue -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!-- 引入Element-ui样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入Element-ui组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
var app = new Vue({
el: '#processboard',
data: {
nowDate:{date:'----',time:'--',week:'--'},
message: 'Hello Vue!',
scrollerHeight1: '90%',
scrollerHeight2: '70%',
showarrow: 'none',
x: 0,
y: 0,
xOffset:0,
yOffset:0,
currentCameraUrl:'http://5b0988e595225.cdn.sohucs.com/images/20180106/f4db5040974a45908fd2d4c741c563ec.jpeg',
drawArea: false,
canDraw: false
},
mounted: function(){
var that = this;
},
filters:{},
watch:{},
computed:{},
methods:{
start: function(){
this.canDraw = true;
},
save: function () {
var fx = this.x;
var fy = this.y;
var fh = this.yOffset;
var fw = this.xOffset;
if(fh == 0 && fw == 0){
alert("请绘制检测区");
return;
}
console.log("x:" + fx);//x轴坐标
console.log("y:" + fy);//y轴坐标
console.log("xWidth:" + fw);//宽度
console.log("yHeight:" + fh);//高度
},
mousedown: function(e){
this.drawArea = true;
if(this.canDraw){
this.x = e.offsetX; // 鼠标落下时的X
this.y = e.offsetY; // 鼠标落下时的Y
this.yOffset = 0;
this.xOffset = 0;
}
},
mouseup: function(e){
this.drawArea = false;
},
mousemove: function(e){
this.drawRect(e);
},
drawRect: function(e){
if(this.drawArea && this.canDraw){
var x = this.x;
var y = this.y;
this.xOffset = e.offsetX-x;
this.yOffset = e.offsetY-y;
this.drawRectWithParam(x,y,this.xOffset,this.yOffset);
}
},
//根据4个参数绘制矩形
drawRectWithParam: function(x,y,width,height){
const canvas = this.$refs.myCanvas;
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
//设置线条颜色,必须放在绘制之前
ctx.strokeStyle = '#00ff00';
// 线宽设置,必须放在绘制之前
ctx.lineWidth = 1;
ctx.strokeRect(x,y,width,height);
},
//清除画的区域
clearArea: function(){
const canvas = this.$refs.myCanvas;
var ctx = canvas.getContext("2d");
this.x = 0;
this.y = 0;
this.yOffset = 0;
this.xOffset = 0;
ctx.clearRect(0,0,canvas.width,canvas.height);
}
}
})
</script>
</body>
</html>
运行结果: