canvas 滑块demo

<moveCom @yzmComfirm="yzmComfirm" ref="moveCom"></moveCom>

/**************************/

<template>
<view>
<canvas @touchend="touchend" @touchmove="touchmove" @touchcancel="touchend" @touchstart="touchstart"
class="canvas" id="canvasIdS" canvas-id="canvasId" style="background-color: #e8e8e8;"></canvas>
</view>
</template>
<script>
export default {
data() {
return {
ok: false,
startX: 0,
moveX: 0,
ctx: null,
cavsWidth: 0,
canMove: true,
count: 0
}
},
onReady() {},
mounted() {
this.getElSize('canvasIdS').then(res => {
this.cavsWidth = res.width
this.ctx = uni.createCanvasContext('canvasId')
this.draw({
positionX: 0
})
})

},
methods: {
getElSize(id) { //得到元素的size
return new Promise((res, rej) => {
uni.createSelectorQuery().select('#' + id).fields({
size: true,
scrollOffset: true
}, (data) => {
res(data);
}).exec();
});
},
draw({
positionX,
width = this.cavsWidth,
fillText = '按住滑块,拖动到最右边',
fillTextColor = '#4d4d4d',
imgPath = "/static/yzmh.png"
}) {
this.ctx.setFillStyle('#7ac23c')
this.ctx.fillRect(0, 0, positionX, 40)
this.ctx.setFillStyle(fillTextColor)
this.ctx.setTextAlign('center')
this.ctx.setTextBaseline('middle')
this.ctx.setFontSize(14)
this.ctx.fillText(fillText, width / 2, 20)
this.ctx.setFillStyle('#fff')
this.ctx.fillRect(positionX, 0, 72, 40)
this.ctx.drawImage(imgPath, positionX, 0, 72, 40)
this.ctx.draw()
},
verifyReset() {
let x = 0;
let a = setInterval(()=>{
x += 10;
if(x >= this.moveX){
clearInterval(a)
this.draw({
positionX:0
})
this.canMove = true;
}
else
this.draw({
positionX: this.moveX - this.startX -x
})
},5)
},
touchend(e) {
if (!this.canMove)
return false;
this.endX = e.changedTouches[0].x;
let lengthX = this.endX - this.startX;
if (lengthX > this.cavsWidth - 100 && this.cavsWidth > lengthX) {
this.draw({
imgPath: "/static/ok.png",
fillText: "验证通过",
fillTextColor: '#fff',
positionX: this.cavsWidth - 72
})
this.canMove = false;
this.$emit("yzmComfirm", true)
} else {
this.verifyReset()
this.count++;
// if(this.count > 2)
// uni.showToast({
// title:"请正确滑动验证"
// })

}
},
touchmove(e) {
if (!this.canMove)
return false;
if (this.startX >= 72)
return false;
this.moveX = e.changedTouches[0].x;
if (this.moveX - this.startX > 0 && this.moveX - this.startX < this.cavsWidth - 40) {
this.draw({
positionX: this.moveX - this.startX
})
}
},
touchstart(e) {
if (!this.canMove)
return false;
this.startX = e.changedTouches[0].x;
}
}
}
</script>

<style>
.canvas {
width: 640rpx;
height: 40px;
border: 1px solid #ccc;
margin-top: 10px;
}
</style>

posted @ 2021-07-06 11:45  mrt_yy  阅读(115)  评论(0编辑  收藏  举报