技术:vue2+vant+canvas
主要解决:van-popup弹框在手机下方显示,canvas没有线条问题
原因:canvas线条的坐标点是从canvas画布计算的,自己获取的坐标点是通过整个页面计算的,通过this.$refs.myCanvas.getBoundingClientRect()
获取canvas画布左上角坐标点
主要:
const vertex = this.$refs.myCanvas.getBoundingClientRect()
this.ctx.lineTo(clientX - vertex.left, clientY - vertex.top);
<van-popup
v-model="canvasShow"
position="bottom"
:style="{ height: '40%' }"
>
<div class="canvasPopup" ref="canvasPopup">
<canvas
class="myCanvas"
ref="myCanvas"
@touchstart="startDrawing"
@touchmove="draw"
@touchend="stopDrawing"
></canvas>
</div>
<div class="canvasBtn">
<van-button type="primary" @click="saveImage">保存</van-button>
<van-button type="default" @click="clearCanvas">清除</van-button>
</div>
</van-popup>
data数据
isDrawing: false,
canvasShow: false,
lastX: 0,
lastY: 0,
ctx: null,
reviewSignature: null,
tagnum: 3,
workFlowOrder: 1
mounted() {
this.draw()
},
startDrawing(e) {
const vertex = this.$refs.myCanvas.getBoundingClientRect()
this.isDrawing = true;
const { clientX, clientY } = e.touches[0];
this.lastX = clientX - vertex.left;
this.lastY = clientY - vertex.top;
},
draw(e) {
if (!this.isDrawing) return;
const vertex = this.$refs.myCanvas.getBoundingClientRect()
const { clientX, clientY } = e.touches[0];
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(clientX - vertex.left, clientY - vertex.top);
this.ctx.stroke();
this.lastX = clientX - vertex.left;
this.lastY = clientY - vertex.top;
},
stopDrawing() {
this.isDrawing = false;
},
//清除按钮
clearCanvas() {
this.ctx.clearRect(0, 0, this.$refs.myCanvas.width, this.$refs.myCanvas.height);
},
//保存按钮
saveImage() {
const dataURL = this.$refs.myCanvas.toDataURL();
console.log(dataURL)
//请求上传部分,省略
this.clearCanvas()
this.canvasShow = false
}