此代码适用于微信SDKVersion"2.9.0 "或以上,以制作半圆形拖动条为例,制作简单的自定义组件的方法流程:
wxml界面配置
在页面里放置一个画布组件
<canvas style="width:300rpx;height:300rpx;position:absolute;left:50rpx;text-align: center;line-height: 300rpx;"
canvas-id="myCanvas"
type="2d"
id="myCanvas"
bindtouchstart="touchstart"
bindtouchmove="touchmove"
bindtouchend="touchend"
bindtouchcancel="touchcancel">
{{progress}}
</canvas>
JS部分代码
全局数据
/**
* 页面的初始数据
*/
data: {
isStart: false,
startprogress: 0,
progress: 0,
halfofcanvas,
isFirst:true
}
触摸监听部分代码
/**
* 点击瞬间触发
*/
touchstart: function (e) {
if (e.changedTouches[0].y <= that.data.halfofcanvas) {
var touchx = Math.abs(e.changedTouches[0].x - this.data.halfofcanvas)
var touchy = this.data.halfofcanvas - e.changedTouches[0].y
var touchr = Math.sqrt((touchx * touchx) + (touchy * touchy))
if (touchr >= this.data.halfofcanvas*0.35 && touchr <= this.data.halfofcanvas) {
this.data.startprogress = this.data.progress;
this.data.isStart = true;
}
}
},
/**
*拖动监听
*/
touchmove: function (e) {
if (this.data.isStart) {
this.changeProgress(e.changedTouches[0].x, e.changedTouches[0].y)
}
this.drawCanvas()
},
/**
*松手监听
*/
touchend: function (e) {
if (this.data.isStart) {
this.changeProgress(e.changedTouches[0].x, e.changedTouches[0].y)
this.data.isStart = false;
}
this.drawCanvas()
},
/**
*触摸事件被打断
*/
touchcancel: function (e) {
//根据需求是否复位拖条
// if (this.data.isStart) {
// this.data.isStart = false;
// this.data.progress = that.data.startprogress
// }
},
/**
*百分比进度计算
*/
changeProgress(x, y) {
//计算角度
const angle = Math.atan((this.data.halfofcanvas - y) / (x - this.data.halfofcanvas)) / Math.PI;
if (y <= this.data.halfofcanvas) {
if (x < this.data.halfofcanvas) {
this.data.progress = ((-1 * angle) * 100).toFixed(0);
} else {
this.data.progress = ((1 - angle) * 100).toFixed(0);
}
} else {
if (x < this.data.halfofcanvas) {
this.data.progress = (angle* 100).toFixed(0);
} else {
this.data.progress = ((1 + angle) * 100).toFixed(0);
}
}
}
以下是绘制部分代码
drawCanvas: function () {
var that = this;
const query = wx.createSelectorQuery();
query.select('#strengthCanvas').fields({
node: true,
size: true
}).exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
if(!that.data.isFirst){
//第一次绘制先确定圆心位置
that.data.halfofcanvas = canvas.width/2
that.data.hasscale = true
}else{
//清空画布,用于重绘时
ctx.clearRect(0, 0, canvas.width, canvas.width)
}
const pro = that.data.progress * 0.01;
//画笔宽度
ctx.lineWidth = canvas.width/40;
ctx.beginPath()
//画布中心画80%画布大小的圆弧
//1代表以9点钟方向为起点,可以根据需求调整
ctx.arc(that.data.halfofcanvas, that.data.halfofcanvas, that.data.halfofcanvas*0.8, 1 * Math.PI, (1 + pro) * Math.PI)
})
}
新手上路笔记,老司机们有更简便的方式欢迎评论指导