在学习canvas中遇到一个问题, 做一个手写板demo的一个过程中
绘制的时候并和鼠标拖的轨迹并不一样, 移动端表现也yiy
如图, 实际上下笔是红色部分
代码如下
<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: '#f7f0e9',
width: '344px',
height: '400px'
}
},
},
data() {
return {
canvas: null,
context: null,
last: null, // 最后一个点
isAllowDrawLine: false, // 是否允许绘制
}
},
mounted: function () {
this.canvas = document.querySelector("#canvas")
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: #f7f0e9;
}
</style>
根据 window.devicePixelRatio 缩放 canvas 试试?