• 使用canvas实现图纸标记及回显


    图纸
    在这里插入图片描述
    图纸标记后的效果图
    在这里插入图片描述
    最近做的一个qms项目里面,需要前端图纸上实现标记标记后的内容还要能够回显,然后后端通过标记的点,去读取标记图纸的内容,如一些公式数据之类的,目前实现的功能有 在图纸上面进行矩形标记已保存的标记回显单个标记点清除一键清除所有标记保存标记图片
    一开始听领导说,小段啊,咱们做的这个项目模块,有个功能图纸标记的功能,需要前端做下,大概就是在图纸上面框住或者圈住一部分,然后传给后端,后端根据你传过去的数据,去读取标记的内容,实现一些其他的业务逻辑。。我一开始是懵逼的,这是啥呀,又搞骚操作??唉,打工人一切向钱看齐,想办法吧,正好前端同时之前做过类似的demo,可以借鉴,同时加上自己的一些琢磨,功能是基本实现,目前还没和后端对接。
    说一下思路:我研究了下,目前在图片上面做一些操作的,大多是通过canvas实现的,canvas的默认背景是黑色的,然后下载后的图片背景就是乌黑黑的一片加一些自己画的线,然后就想着把图纸作为canvas的背景图片,这样下载后的背景图片就是图纸,挺好的,哈哈,剩下的具体代码实现的逻辑,都在贴在下面的代码示例里面了!!

    以下是操作视频

    图纸标记组件视频

    代码如下

    <template>
      <div>
        <div>
          <a-button @click="clearBtn" style="margin-right:15px;">清除当前标记</a-button>
          <a-button @click="clearAllBtn" style="margin-right:15px;">清除所有标记</a-button>
          <a-button @click="saveBtn" type="primary" style="margin-right:15px;">保存标记</a-button>
          <a-button @click="saveImage" type="primary">下载标记图片</a-button>
        </div>
        <div style="margin:10px 0">
          <a-form :model="formInfo" ref="formRef" name="basic" :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }">
            <a-row :gutter="20">
              <a-col :span="8">
                <a-form-item label="标记名称" name="rectName">
                  <a-input v-model:value="rectName" placeholder="请输入标记名称" allowClear></a-input>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div id="canvasDiv">
          <canvas ref="canvas"  @contextmenu.prevent="canvasRight" @mousedown="startMark" @click="canvasClick" @mousemove="draw" @mouseup="endMark"></canvas>
        </div>
      </div>
    </template>
     
    <script>
    import cardPng from '/@/assets/images/card.png';
    
    export default {
      data() {
        return {
          isMarking: false,//是否开始在标记的标识
          startX:0,//点击时初始位置x轴
          startY:0,//点击时初始位置y轴
          markedRectangles: [
            {x:162, y:253, width:46, height:76,name:'过渡板'},
            {x:70, y:253, width:47, height:70,name:'电磁阀'},
            {x:447, y:928, width:114, height:39,name:'软管'},
          ], // 存储已标记矩形的数组
          rectObj:'',//记录最后一次的矩形
          rectName:'',//标记名称
        };
      },
      mounted() {
        //设置canvas背景
        this.loadCanvas();
        window.addEventListener('resize', this.loadCanvas);
      },
      beforeDestroy() {
        window.removeEventListener('resize', this.loadCanvas);
      },
      methods: {
        canvasRight(e){
          e.preventDefault();// 阻止默认的右键菜单
        },
        //下载标记并且保存的canvas图片
        saveImage(){
          this.drawBackground();//重绘canvas及回显保存的标记,若是标记未保存,则不会在下载的图片里面显示
          const img = this.canvas.toDataURL('image/png');
          const link = document.createElement('a');
          link.href = img;
          link.download = 'canvas.png';
          console.log(img,'img')
          console.log(link,'link')
          link.click();
        },
        canvasClick(event){
          // cavans点击事件监听
          console.log(event,'event')
          const canvas = this.$refs.canvas;
          const ctx = canvas.getContext('2d');
          const rect = canvas.getBoundingClientRect();
          const x = event.clientX - rect.left;
          const y = event.clientY - rect.top;
          // 遍历已标记的矩形,检查点击位置,若是在标记数组的矩形范围内,则从数组中进行比对,进行标记名称回显
          for (let i = this.markedRectangles.length - 1; i >= 0; i--) {
            const markedRect = this.markedRectangles[i];
            if (x >= markedRect.x &&x <= markedRect.x + markedRect.width && y >= markedRect.y && y <= markedRect.y + markedRect.height){
              this.rectObj=markedRect;
              this.rectName=markedRect.name;
            }
          }
        },
        
        //绘制canvas、添加背景图片、把标记数组里面的点回显
        drawBackground(){
          this.canvas.width = this.image.width;
          this.canvas.height = this.image.height;
          this.ctx.drawImage(this.image, 0, 0);
          this.ctx.strokeStyle = '#99eb1e';//改变画线的颜色和宽度
          this.ctx.lineWidth = 2;
          this.markedRectangles.forEach((item,index)=>{
            item.resetid=new Date().getTime()+index;
          })
          console.log(this.markedRectangles,'markedRectangles')
          for(let i=0;i<this.markedRectangles.length;i++){
            this.ctx.strokeRect(this.markedRectangles[i].x, this.markedRectangles[i].y, this.markedRectangles[i].width, this.markedRectangles[i].height)//起点/终点/宽度/高度
          }
        },
        //赋值初始值x轴的点、y轴的点
        startMark(event) {
          this.isMarking = true;//开始标记,记录此时开始标记的初始点
          const rect = this.canvas.getBoundingClientRect();
          this.startX = event.offsetX;
          this.startY = event.offsetY;
        },
        //标记中
        draw(event) {
          if (this.isMarking) {
            //获取最后标记的位置,拿最后标记的位置的x轴值、y轴值与初始位置的x轴值,与y轴值进行计算,获取标记矩形的宽高
            const rect = this.canvas.getBoundingClientRect();
            const x = event.offsetX - this.startX;
            const y = event.offsetY - this.startY;
            //canvas绘制时,会把背景图清掉,需要再次调用下添加背景图的方法
            this.drawBackground();
            this.ctx.strokeRect(this.startX, this.startY, x, y);
            this.rectObj={x:this.startX, y:this.startY,width: x,height:y};//把最后的标记矩形的位置及宽高记录,若是保存此时的标记,会用到
          }
        },
        //标记结束
        endMark() {
          this.isMarking = false;//重置标记标识为false
        },
        // 初始化canvas
        loadCanvas(){
          this.canvas = this.$refs.canvas;
          this.ctx = this.canvas.getContext('2d');
          this.image = new Image();
          this.image.src = cardPng; // 替换为你的图片路径
          let canvasDiv=document.getElementById("canvasDiv");
          this.image.onload = () => {
            this.drawBackground();
          };
        },
        saveBtn(){
          // 保存时,若是此时的矩形存在,则添加到标记数组里面
          console.log(this.rectObj,'rectObj')
          if(this.rectObj!=''){
            let that=this;
            //防止同一个标记被保存多次
            for(let i=0;i<this.markedRectangles.length;i++){
              if(this.markedRectangles[i].x!=that.rectObj.x&&this.markedRectangles[i].y!=that.rectObj.y&&this.markedRectangles[i].width!=that.rectObj.width&&this.markedRectangles[i].height!=that.rectObj.height){
                if(this.rectName){
                  that.rectObj.name=this.rectName;
                  that.markedRectangles.push(that.rectObj)
                  that.$message.success('该标记已保存')
                  that.rectObj='';
                  return false
                }else{
                  this.$message.warning('请输入标记名称')
                }
              }
            }
          }else{
            this.$message.warning('暂无标记可以保存')
            return false
          }
          console.log(this.markedRectangles,'markedRectangles')
        },
        //清除标记
        clearBtn(){
          //重绘canvas
          // 若是有resetid,则是已保存过的,若是没有resetid,则是后来新增的
          if(this.rectObj!=''){
            if(this.rectObj.resetid){
              // this.rectObj='';
              this.$confirm('确定删除?', '提示', {
                okText: '确定',
                cancelText: '取消',
                type: 'warning'
              }).then(() => {
                for(let i=0;i<this.markedRectangles.length;i++){
                  if(this.markedRectangles[i].x==this.rectObj.x&&this.markedRectangles[i].y==this.rectObj.y&&this.markedRectangles[i].width==this.rectObj.width&&this.markedRectangles[i].height==this.rectObj.height){
                    this.rectName='';
                    this.rectObj='';
                    this.markedRectangles.splice(i, 1); // 从数组中移除
                    this.$message.success('标记已清除')
                    this.drawBackground();
                    return false
                  }
                }
              }).catch(() => {
                this.$message({
                  type: 'warning',
                  message: '已取消删除'
                });          
              });
              
            }else{
              this.drawBackground();
              this.rectObj='';
              this.$message.warning('标记已清除')
              return false
            }
          }else{
            this.$message.warning('暂无标记可以清除')
          }
    
        },
        //一键清除所有标记
        clearAllBtn(){
          //把标记数组清空,同时重绘canvas
          if(this.markedRectangles.length>0){
            this.markedRectangles=[];
            this.drawBackground();
          }else{
            this.$message.warning('暂无标记可以清除')
            return false
          }
        },
      }
    };
    </script>
    <style scoped>
    #canvasDiv{
      width:800px;
      height: auto;
    }
    </style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
  • 相关阅读:
    ubuntu 18.04 OAK-D系列相机运行VINS-Fusion 双目+IMU
    自动驾驶 - 滤波算法
    走访喜开路 | 共建全民大健康元宇宙服务体系预立项
    如何让你的Node.js应用程序处理数百万的API请求
    DyGRAIN: An Incremental Learning Framework for Dynamic Graphs
    渗透测试高级技巧(二):对抗前端动态密钥与非对称加密防护
    java计算机毕业设计可视化工器具信息管理系统源码+mysql数据库+系统+lw文档+部署
    c语言:模拟实现qsort函数
    服务器防漏扫,主机加固方案来解决
    什么是 RPA?
  • 原文地址:https://blog.csdn.net/blue__k/article/details/136717677