场景
物联网项目中需要测试手机屏幕的连续性(猜的)通过手指在屏幕上画直线和曲线,看是否出现断点。
代码
<template>
<div @touchmove="touchmove" @touchstart="touchstart">
<canvas ref="canvas" width="800" height="286"></canvas>
</div>
</template>
<script>
export default {
data () {
return {
context: {},
screenY: 0,
screenX: 0,
pointList: [],
}
},
methods: {
initCanvas () {
const c = this.$refs.canvas;
// eslint-disable-next-line no-undef
this.context = typeof createCanvasContext === 'function' ? createCanvasContext(c) : c.getContext('2d');
},
drawline (sx, sy, ex, ey, color, isDash) {
// set dash
this.context.beginPath() // 加此语句线路才能被clearRect清除
this.context.strokeStyle = color
this.context.moveTo(sx, sy)
this.context.lineTo(ex, ey)
this.context.stroke()
},
getBeginAndEndPoint () {
let length = this.pointList.length;
let sx = this.pointList[0].screenX;
let sy = this.pointList[0].screenY;
let ex = this.pointList[length - 1].screenX;
let ey = this.pointList[length - 1].screenY;
let color = '#f10215'
this.drawline(sx, sy, ex, ey, color)
},
touchstart (e) {
// 每次开始画线,清除上次的点
this.pointList = []
},
touchmove (e) {
this.context.clearRect(0, 0, 800, 268)
//浏览器上screenX变成clientX,浏览器上screenY变成clientY,e.changedTouches变成e.touches
// this.clientX = e.touches[0].clientX;
// this.clientY = e.touches[0].clientY;
this.screenX = e.changedTouches[0].screenX;
this.screenY = e.changedTouches[0].screenY;
this.pointList.push(
{
screenX: this.screenX,
screenY: this.screenY
}
)
this.getBeginAndEndPoint()
}
},
mounted () {
this.initCanvas();
},
}
</script>
<style>
</style>