pc事件:mousedown,mousemove,mouseup
移动事件:touchstart,touchmove,touchend
<canvas id="canvas" ref="canvas"></canvas>
data的数据
data () {
return {
toDataURL: null,
canvasRect: null, // canvas元素大小
startX: 0,
startY: 0,
endX: 0,
endY: 0,
isDown: false // 鼠标是否按下
}
}
pc写法
mounted() {
this.$nextTick(() => {
this.init()
// 初始化存下画布数据
this.toDataURL = this.$refs.canvas.toDataURL()
})
},
methods: {
init() {
const canvas = this.$refs.canvas
this.canvasRect = canvas.getBoundingClientRect()
// 设置canvas画布大小
canvas.setAttribute('width', this.canvasRect.width)
canvas.setAttribute('height', this.canvasRect.height)
const ctx = canvas.getContext('2d')
// 设置画布粗细,颜色,字体等
ctx.lineWidth = 5
canvas.addEventListener('mousedown', (e) => {
e.preventDefault()
this.startX = e.clientX - this.canvasRect.left
this.startY = e.clientY - this.canvasRect.top
ctx.beginPath()
this.isDown = true
}, false)
canvas.addEventListener('mousemove', (e) => {
e.preventDefault()
if (this.isDown) {
this.endX = e.clientX - this.canvasRect.left
this.endY = e.clientY - this.canvasRect.top
ctx.moveTo(this.startX, this.startY)
ctx.lineTo(this.endX, this.endY)
ctx.stroke()
this.startX = this.endX
this.startY = this.endY
}
}, false)
canvas.addEventListener('mouseup', (e) => {
e.preventDefault()
ctx.closePath()
this.isDown = false
}, false)
},
submit() {
if (this.toDataURL === this.$refs.canvas.toDataURL()) {
this.$message.warning('请先在签名框内签名,然后点击确认按钮')
return false
}
},
// 清空
clear() {
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')
const W = this.canvasRect.width
const H = this.canvasRect.height
ctx.clearRect(0, 0, W, H)
}
}
移动写法
methods: {
init() {
const canvas = this.$refs.canvas
this.canvasRect = canvas.getBoundingClientRect()
// 设置canvas画布大小
canvas.setAttribute('width', this.canvasRect.width)
canvas.setAttribute('height', this.canvasRect.height)
const ctx = canvas.getContext('2d')
canvas.addEventListener('touchstart', (e) => {
e.preventDefault()
this.startX = e.targetTouches[0].clientX - this.canvasRect.left
this.startY = e.targetTouches[0].clientY - this.canvasRect.top
}, false)
canvas.addEventListener('touchmove', (e) => {
e.preventDefault()
this.endX = e.targetTouches[0].clientX - this.canvasRect.left
this.endY = e.targetTouches[0].clientY - this.canvasRect.top
this.draw(ctx)
this.startX = this.endX
this.startY = this.endY
}, false)
},
draw(ctx, startX, startY, endX, endY) {
ctx.lineWidth = 5
ctx.beginPath()
ctx.moveTo(this.startX, this.startY)
ctx.lineTo(this.endX, this.endY)
ctx.closePath()
ctx.stroke()
}
}