var canvas = document.getElementById('canvas') // 獲取元素
canvas.width = '560'
canvas.height = '244'
var img = new Image()
img.src = require('../img/mask.png') // 默認(rèn)的背景圖片
var ctx = canvas.getContext('2d') // 生成畫布
img.onload = function() {
ctx.drawImage(img, 0, 0)
ctx.globalCompositeOperation = 'destination-out' // 橡皮擦
}
// ctx.strokeStyle = '#FDF5EA' // 線的顏色
let pos = 0, // 手指總共劃過的距離
x = 0, // x軸走過的距離
y = 0 // y軸走過的距離
ctx.beginPath() // 開始
ctx.lineWidth = 120 // 線的寬度
var canvaL = canvas.getBoundingClientRect().left //
var canvaT = canvas.getBoundingClientRect().top // 160是margin-top的距離
var _this = this
function bodyScroll(event) { // 默認(rèn)事件 點(diǎn)擊canvas時(shí)屏幕不跳動(dòng)
event.preventDefault();
}
let startX = 0, // 手指開始的位置
startY = 0,
moveX = 0, // 手指移動(dòng)的位置
moveY = 0,
num = 0 // 用他來做數(shù)據(jù)請求的條件
canvas.ontouchstart = function (e) {
// 手指按下位置
startX = e.touches[0].pageX
startY = e.touches[0].pageY
ctx.moveTo(startX - canvaL, startY - canvaT) // 線條開始
document.body.addEventListener('touchmove', bodyScroll, false);
}
canvas.ontouchmove = function (e) {
// 手指移動(dòng)位置
moveX = e.touches[0].pageX
moveY = e.touches[0].pageY
ctx.lineTo(moveX - canvaL, moveY - canvaT) // 線條到達(dá)位置
// 計(jì)算手指移動(dòng)的距離
x = (startX - moveX)
y = (startY - moveY)
pos += Math.abs(x)
pos += Math.abs(y)
num++
if (num === 1) {
_this.shaveData() // 數(shù)據(jù)請求
}
ctx.stroke() // 結(jié)束
}
canvas.ontouchend = function (e) {
ctx.stroke() // 結(jié)束
document.body.removeEventListener('touchmove', bodyScroll, false);
// 手指抬起的位置
let endX = startX - e.changedTouches[0].pageX,
endY = startY - e.changedTouches[0].pageY
if (pos >= 3000) {
_this.state = 4
_this.$refs.canvas.style.zIndex = '-20'
_this.$refs.canvas.style.visibility = 'hidden'
canvas.width = canvas.width
canvas.height = canvas.height
ctx.lineWidth = 120
var img = new Image()
img.src = require('../img/mask.png')
img.onload = function () {
ctx.drawImage(img, 0, 0)
ctx.globalCompositeOperation = 'destination-out';
}
pos = 0
x = 0
y = 0
num = 0
}
}
實(shí)現(xiàn)的效果就是其實(shí)就是用橡皮擦擦掉了一個(gè)圖層 把你需要的信息房在下面 這樣就
能刮出東西來了