Vue使用滑鼠在Canvas上繪製矩形
阿新 • • 發佈:2020-12-27
本文例項為大家分享了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,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.執行截圖
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。