0
点赞
收藏
分享

微信扫一扫

框选标注拾取坐标

丹柯yx 2022-01-13 阅读 55
<template>
  <div id="container"></div>
</template>

<script>
export default {
  name: 'Container',
  data() {
    return {
      containerDom: null,
      cavDom: null,
    }
  },

  mounted() {
    this.init()
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },

  methods: {
    init() {
      this.containerDom = document.getElementById('container')
      this.cavDom = document.createElement('canvas')
      this.cavDom.width = this.containerDom.offsetWidth
      this.cavDom.height = this.containerDom.offsetHeight
      this.cavDom.id = 'canvasDom'
      this.cavDom.style.cursor = 'crosshair'
      this.containerDom.appendChild(this.cavDom)
      window.addEventListener('resize', this.handleResize)

      this.draw()
    },

    draw() {
      const ctx = this.cavDom.getContext('2d') // 一个 CanvasRenderingContext2D 对象,使用它可以绘制到 Canvas 元素中
      ctx.strokeStyle = '#2080F7' // 用于笔触的颜色、渐变或模式
      ctx.lineWidth = 2 // 当前线条的宽度,以像素计

      let start = false // 画框状态, false时不执行画框操作
      let sX = 0 // 鼠标X坐标
      let sY = 0 // 鼠标Y坐标

      /* 按下鼠标左键 */
      this.cavDom.onmousedown = ed => {
        start = true
        sX = ed.offsetX
        sY = ed.offsetY

        /* 鼠标移动 */
        this.cavDom.onmousemove = em => {
          if (start) {
            // 清空画布
            ctx.clearRect(0, 0, this.cavDom.width, this.cavDom.height)

            // ctx.clearRect(sX, sY, em.offsetX - sX, em.offsetY - sY)
            ctx.beginPath()
            // 设置边框为虚线
            ctx.setLineDash([8, 4])
            ctx.rect(sX, sY, em.offsetX - sX, em.offsetY - sY)
            ctx.stroke()
          }
        }

        this.cavDom.onmouseup = eu => {
          if (start) {
            ctx.beginPath() // 开始一条路径,或重置当前的路径
            // 设置边框为实线
            ctx.setLineDash([])
            ctx.rect(sX, sY, eu.offsetX - sX, eu.offsetY - sY)
            ctx.stroke()

            // 改变画框状态
            start = false

            console.log(sX, sY, eu.offsetX, eu.offsetY)
          }
        }
      }
    },

    handleResize() {
      this.cavDom.width = this.containerDom.offsetWidth
      this.cavDom.height = this.containerDom.offsetHeight
    },
  },
}
</script>

<style lang="scss">
#container {
  width: 100%;
  height: 100%;
  background-color: antiquewhite;
}
</style>
举报

相关推荐

0 条评论