前言
uniapp canvas刮刮乐 uniapp canvas 刮刮乐提示:以下是本篇文章正文内容,下面案例可供参考
一、使用步骤
1.页面
代码如下(示例):
<template>
<view class="canvasView">
<view class="imgbox">
<image src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1295848413,2583684724&fm=26&gp=0.jpg" mode=""></image>
<canvas class="canvas1" id="canvas1" canvas-id="canvas1" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
</view>
</view>
</template>
<script>
export default {
data() {
return {
viewWidth: 0,
viewHeight: 0,
ctx: null,
x: [],
y: [],
points: []
}
},
mounted() {
this.drawInit()
},
methods: {
touchstart(e) {
let startX = e.changedTouches[0].x;
let startY = e.changedTouches[0].y;
let startPoint = {
x: startX,
y: startY
};
//存点 一起画
this.points.push(startPoint);
//每次触摸开始,开启新的路径F
this.ctx.beginPath();
},
touchmove(e) {
let moveX = e.changedTouches[0].x
let moveY = e.changedTouches[0].y
let movePoint = {
x: moveX,
y: moveY,
}
this.points.push(movePoint)
if (this.points.length >= 2) {
this.drawLine()
}
},
touchend(e) {
this.points = []
// console.log(e, 'touchend');
},
// 获取元素宽高
getViewHW() {
let info = uni.createSelectorQuery().in(this).select(".imgbox");
return new Promise((resolve, reject) => {
info.boundingClientRect((data) => {
this.viewWidth = data.width
this.viewHeight = data.height
resolve()
}).exec(function(res) {
// 注意:exec方法必须执行,即便什么也不做,否则不会获取到任何数据
})
})
},
drawLine() {
let points1 = this.points[0]
let points2 = this.points[1]
this.points.shift()
this.ctx.moveTo(points1.x, points1.y)
this.ctx.lineTo(points2.x, points2.y)
this.ctx.stroke()
this.ctx.draw(true)
},
async drawInit() {
await this.getViewHW()
this.ctx = uni.createCanvasContext('canvas1')
let x = this.viewWidth
let y = this.viewHeight
// let x = 400
// let y = 400
console.log(x, y);
this.ctx.setFillStyle('#eeeeee')
this.ctx.fillRect(0, 0, x, y)
this.ctx.setFontSize(30)
this.ctx.setTextBaseline('middle')
this.ctx.setFillStyle('black')
this.ctx.setTextAlign('center')
this.ctx.fillText('刮刮乐刮刮乐刮刮乐', x / 2, y / 2)
this.ctx.lineWidth = 4;
this.ctx.lineCap = "round"
this.ctx.lineJoin = "round"
this.ctx.draw(true)
//接下来线的样式
this.ctx.lineWidth = 40; //刮的大小
this.ctx.lineCap = "round"
this.ctx.lineJoin = "round"
this.ctx.globalCompositeOperation = 'destination-out' //关键是这个属性
}
}
}
</script>
<style lang="scss" scoped>
.canvasView {
width: 100%;
height: 100%;
.imgbox {
position: relative;
margin-top: 100rpx;
width: 100%;
height: 950rpx;
image {
height: 100%;
width: 100%;
}
.canvas1 {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
}
}
</style>
效果展示
总结
1.uni.createSelectorQuery().in(this).select(".imgbox");
app真机调试获取元素宽高比h5慢
2.参考canvas签名效果实现刮刮乐,关键:
this.ctx.globalCompositeOperation = ‘destination-out’ 与h5的使用方式差不多