场景
物联网项目中需要测试手机屏幕的连续性(猜的)通过手指在屏幕上画直线和曲线,看是否出现断点。
代码
<template>
<div @touchmove="touchmove" @touchstart="touchstart">
<canvas ref="canvas" width="800" height="286" />
</div>
</template>
<script>
export default {
data() {
return {
context: {},
screenX: 0,
screenY: 0,
pointList: [],
point: {}
}
},
mounted() {
this.initCanvas()
},
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.fillStyle = '#f10215'
this.context.lineWidth = 4;
// 绘制成矩形
this.context.fillRect(ex - 2, ey - 2, 2, 2)
this.context.stroke()
},
getDiffLineColor() {
const length = this.pointList.length
const sx = this.pointList[length - 1].screenX
const sy = this.pointList[length - 1].screenY
let ex = this.pointList[length - 1].screenX
let ey = this.pointList[length - 1].screenY
if (length >= 2) {
ex = this.pointList[length - 2].screenX
ey = this.pointList[length - 2].screenY
}
const standard = Math.pow(ex - sx, 2) + Math.pow(ey - sy, 2)
console.log(standard, '--------')
let color
if (standard > 150) {
color = '#7fff00'
} else if (standard > 50 && standard < 150) {
color = '#0000ff'
} else {
color = '#f10215'
}
this.drawline(sx, sy, ex, ey, color)
},
touchmove(e) {
console.log(e, '------')
// document.addEventListener('touchmove', (e) => {
this.screenX = e.changedTouches[0].screenX
this.screenY = e.changedTouches[0].screenY
this.pointList.push(
{
screenX: this.screenX,
screenY: this.screenY
}
)
this.getDiffLineColor()
},
touchstart() {
this.context.clearRect(0, 0, 800, 268)
this.pointList = []
}
}
}
</script>
<style>
</style>