canvas-(4):鼠标事件 画单个矩形

2020-11-04  本文已影响0人  小北呀_
<template>
  <div class="box">
    <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,
      }
    },
    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,'移动中')

        if(this.flag){
          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.ctx.beginPath();
          //设置线条颜色,必须放在绘制之前
          this.ctx.strokeStyle = 'block';
          // 线宽设置,必须放在绘制之前
          this.ctx.lineWidth = 1;
          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
      }
    }
  }
</script>
<style scoped>
.box{
  width: 100%;
  height: 100%;
  position: relative;
}
.bg{
  width: 500px;
  height: 500px;
  position: absolute;
  top: 0;
  left: 50px;
  background: pink;
  /* 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>
上一篇 下一篇

猜你喜欢

热点阅读