在微信小程序中 实现摇杆组件
//recker.js
let oldStellungDerWippe = "";
Component({
properties: {
// 图像大小
size: {
type: Number,
value: 100,
},
coordinates_x: {
type: Number,
value: 0,
},
coordinates_y: {
type: Number,
value: 0,
},
},
data: {
x: 0,
y: 0,
radius: 90,
},
methods: {
touchMove(e) {
const data = this.data;
// 触摸时的坐标减去 当前组件在屏幕上的位置(coordinates_x,coordinates_x)
// 减去半径
let x = e.touches[0].clientX - data.coordinates_x - data.size / 2;
let y = e.touches[0].clientY - data.coordinates_y - data.size / 2;
let angle = Math.atan2(y, x);
// 计算半径
let radius = Math.sqrt(x * x + y * y);
if (radius > data.radius) {
x = Math.cos(angle) * data.radius;
y = Math.sin(angle) * data.radius;
}
let sideLength = data.size / 2 / 2 / 2;
// console.log("sideLength",sideLength);
// 摇杆在中间不做任何操作
if (
!(
x <= sideLength &&
x >= -sideLength &&
y <= sideLength &&
y >= -sideLength
)
) {
// 竖线
if (x >= -sideLength && x < sideLength) {
if (y >= -sideLength) {
if (oldStellungDerWippe != "button") {
oldStellungDerWippe = "button";
console.log(oldStellungDerWippe);
}
} else {
if (oldStellungDerWippe != "top") {
oldStellungDerWippe = "top";
console.log(oldStellungDerWippe);
}
}
} else if (y >= -sideLength && y < sideLength) {
// 横线
if (x <= sideLength) {
if (oldStellungDerWippe != "left") {
oldStellungDerWippe = "left";
console.log(oldStellungDerWippe);
}
} else {
if (oldStellungDerWippe != "right") {
oldStellungDerWippe = "right";
console.log(oldStellungDerWippe);
}
}
}
}
this.setData({
x: x,
y: y,
});
},
// 手松开回到原点
touchEnd() {
this.setData({
x: 0,
y: 0,
});
},
},
});
//recker.wxml
<view class="background">
<view class="container" style="width: {{size}}px; height: {{size}}px;">
<image src="/image/happy.png" class="joystick" catchtouchmove="touchMove" catchtouchend="touchEnd" style="transform: translate({{x}}px, {{y}}px)"></image>
</view >
</view>
//recker.wxss
.background {
background-color: aqua;
width: 200px;
height: 200px;
}
.container {
position: relative;
/* border-radius: 50%; */
/* padding: 20px; */
}
.joystick {
position: absolute;
top: 50%;
left: 50%;
width: 50%;
height: 50%;
/* margin 数值是高度的一半的绝对值 ,如 width 20% margin-top: -25%;*/
margin-top: -25%;
margin-left: -25%;
border-radius: 50%;
}
//调用组件
<rocket size="200" coordinates_y=""></rocket>