encountered a problem in learning canvas, in the process of making a tablet demo
, yiy
,
the code is as follows
<template>
<div>
<canvas id="canvas"
@touchstart="drawStart"
@touchend="drawEnd"
@touchmove="drawing"
@mousedown="drawStart"
@mouseup="drawEnd"
@mousemove="drawing"
v-bind:style="{background: canvasAttr.bgColor, width: canvasAttr.width, height: canvasAttr.height}">
</canvas>
<el-row>
<el-col>
<el-button @click="save"></el-button>
<el-button @click="clear"></el-button>
</el-col>
</el-row>
</div>
</template>
<script>
export default {
name: "singCanvas",
props: {
canvasAttr: {
type: Object,
default: {
bgColor: "-sharpf7f0e9",
width: "344px",
height: "400px"
}
},
},
data() {
return {
canvas: null,
context: null,
last: null, //
isAllowDrawLine: false, //
}
},
mounted: function () {
this.canvas = document.querySelector("-sharpcanvas")
this.context = this.canvas.getContext("2d")
},
methods: {
save() {
this.canvas.clearRect(0, 0, this.canvas.width, this.canvas.height)
},
clear() {
},
drawStart(event) {
this.isAllowDrawLine = true
},
drawing(event) {
console.log("drawing")
event.preventDefault()
if (!this.isAllowDrawLine) {
return;
}
let xy = this.getCoordinate(event)
console.log(xy)
if (this.last !== null) {
console.log(this.last)
this.context.beginPath();
this.context.moveTo(this.last.x, this.last.y);
this.context.lineTo(xy.x, xy.y);
this.context.stroke();
}
this.last = xy
},
drawEnd(event) {
console.log("draw end")
event.preventDefault()
this.isAllowDrawLine = false
this.last = null
},
getCoordinate(e) {
let rect = this.canvas.getBoundingClientRect();
let x, y
if (this.isTouch(e)) {
x = e.touches[0].pageX
y = e.touches[0].pageY
} else {
x = e.offsetX + e.target.offsetLeft;
y = e.offsetY + e.target.offsetTop
}
console.log(x, y)
return {
x: x,
y: y
}
},
isTouch(e) {
const type = e.type
let flag = type.indexOf("touch") >= 0
console.log(flag ? "" : "pc")
return flag
},
},
watch: {}
}
</script>
<style scoped>
html {
background-color: -sharpf7f0e9;
}
</style>