Vue中使用鼠標在Canvas上繪製矩形

1.代碼

<template>
  <div class="test" style="background-color: burlywood;">
    <canvas id="myCanvas" ref="myCanvas"
            width="460" height="240" @mousedown="mousedown" @mouseup="mouseup" @mousemove="mousemove">
    </canvas>
  </div>
</template>

<script>
  export default {
    name:"hello-world",
    data() {
      return {
        flag: false,
        x: 0,
        y: 0
      };
    },
    watch: {},
    computed: {},
    methods: {
      mousedown(e){
        console.log("鼠標落下");
        this.flag = true;
        this.x = e.offsetX; // 鼠標落下時的X
        this.y = e.offsetY; // 鼠標落下時的Y
      },
      mouseup(e){
        console.log("鼠標擡起");
        this.flag = false;
      },
      mousemove(e){
        console.log("鼠標移動");
        this.drawRect(e);
      },
      drawRect(e){
        if(this.flag){
          console.log("繪製圖形");
          const canvas = this.$refs.myCanvas;
          var ctx = canvas.getContext("2d");
          let x = this.x;
          let y = this.y;

          ctx.clearRect(0,0,canvas.width,canvas.height);
          ctx.beginPath();

          //設置線條顏色,必須放在繪製之前
          ctx.strokeStyle = '#00ff00';
          // 線寬設置,必須放在繪製之前
          ctx.lineWidth = 1;

          ctx.strokeRect(x,y,e.offsetX-x,e.offsetY-y);
        }
      }
    },
    created() {

    },
    mounted() {

    }
  };
</script>

<style scoped>
  #myCanvas{
    background-color: forestgreen;
    background-image:url('../bg.jpg');
  }
</style>

2.運行截圖

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章