使用鼠标在Canvas上绘制矩形
前言
最近接到一个项目,要求在图像上画框 圈监测范围,发现如下方案可快速实现,特此记录。
代码如下:
<template><div><canvas id="myCanvas" ref="myCanvas" :width="canvasWidth" :height="canvasHeight" class="canvas-box" @mousedown="mousedown" @mouseup="mouseup" @mousemove="mousemove"></canvas></div>
</template><script>export default {name:"",data() {return {canvasFlag: false,canvasWidth: 491,canvasHeight: 276,startPos:[0,0],endPos:[0,0],};},methods: {mousedown(e){// console.log("鼠标落下");this.canvasFlag = true;this.startPos=[e.offsetX,e.offsetY] // 鼠标落下时的X,Y},mouseup(e){// console.log("鼠标抬起");this.canvasFlag = false;},mousemove(e){// console.log("鼠标移动");this.drawRect(e);},drawRect(e){if(this.canvasFlag){const canvas = this.$refs.myCanvas;var ctx = canvas.getContext("2d");let x = this.startPos[0];let y = this.startPos[1];this.endPos=[e.offsetX,e.offsetY]ctx.clearRect(0,0,canvas.width,canvas.height);ctx.beginPath();//设置线条颜色,必须放在绘制之前ctx.strokeStyle = '#ff0000';// 线宽设置,必须放在绘制之前ctx.lineWidth = 2;ctx.strokeRect(x,y,e.offsetX-x,e.offsetY-y);console.log("绘制图形",this.startPos,this.endPos);}}},};
</script>