Vue使用鼠標在Canvas上繪制矩形
更新時間:2020年12月24日 09:58:27 作者:小諸葛的博客
這篇文章主要介紹了Vue使用鼠標在Canvas上繪制矩形,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Vue使用鼠標在Canvas上繪制矩形的具體代碼,供大家參考,具體內(nèi)容如下
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();
//設(shè)置線條顏色,必須放在繪制之前
ctx.strokeStyle = '#00ff00';
// 線寬設(shè)置,必須放在繪制之前
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.運行截圖

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決vant的Toast組件時提示not defined的問題
這篇文章主要介紹了解決vant的Toast組件時提示not defined的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
vue中實現(xiàn)監(jiān)聽數(shù)組內(nèi)部元素
這篇文章主要介紹了vue中實現(xiàn)監(jiān)聽數(shù)組內(nèi)部元素方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
JS 函數(shù)的 call、apply 及 bind 超詳細方法
這篇文章主要描述JS 函數(shù)的 call、apply 及 bind 方法的超詳細解說,感興趣的朋友可以參考下文,希望能幫助到您2021-08-08

