闲来无事正好团队准备做一个画板相关的项目,虽然我不在其中但是对这个画板还是蛮有兴趣的。
主要是通过canvas这个标签加上鼠标的一些相关事件来实现的。
中间有碰到过一个bug
canvas的画板大小不能通过css来设置,css会缩放大小导致获取到的点坐标是正确的但是在canvas上显示的位置确是有偏差的
这里的解决办法是直接在canvas标签上的width和height设置长和宽。
<template>
<div class="canvas">
<button @click="resetCanvas">清空canvas</button>
<canvas width="500px" height="300px" ref="canvas"></canvas>
</div>
</template>
<script>
export default {
name: "canvas",
components: {},
data() {
return {};
},
mounted() {
this.init();
},
methods: {
init() {
let canvas = this.$refs.canvas
let ctx = canvas.getContext("2d")
let startPosition = []
let isdraw = false
ctx.fillStyle = "#999999"
ctx.fillRect(0, 0, 500, 300)
ctx.lineWidth = 1
canvas.onmousedown = res => {
//指针在canvas上点击
isdraw = true;
startPosition[0] = res.offsetX
startPosition[1] = res.offsetY
drawLine(res.offsetX,res.offsetY)
console.log(res)
};
canvas.onmouseup = res => {
//指针在canvas上放开
if (!isdraw) return;
clear()
};
canvas.onmouseout = res => {
//指针移出canvas
if (!isdraw) return;
clear()
};
canvas.onmousemove = res => {
//指针在canvas移动
if (!isdraw) return;
drawLine(res.offsetX,res.offsetY)
};
function drawLine(X,Y) {
//画图
if (!isdraw) return;
ctx.beginPath();
console.log(X,Y)
ctx.moveTo(startPosition[0],startPosition[1])
startPosition = [X,Y]
ctx.lineTo(X,Y);
ctx.stroke();
ctx.save()
}
function clear() {
isdraw = false;
startPosition = []
}
},
resetCanvas() {
//清空canvas
let canvas = this.$refs.canvas
let ctx = canvas.getContext("2d")
let startPosition = []
let isdraw = false
ctx.fillStyle = "#999999"
ctx.fillRect(0, 0, 500, 300)
}
}
};
</script>
<style lang='scss' scoped>
canvas {
}
</style>
哈哈字有点丑~~~但是问题不大!!!
打开App,阅读手记