Vue使用鼠標在Canvas上繪制矩形

本文實例為大傢分享瞭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.運行截圖

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: