小程序的加速度计是个很有意思的东西,可以用来做一些手机动作或3D场景。比如手机QQ上的附近的红包活动就是采用加速度计做的。这里写个demo初步做一下加速度计的使用方法。主要步骤:
1、在页面onLoad的时候检测加速度计是否可用。
2、监听加速度计的返回参数(x,y,z)三轴。
3、根据不同的场景去处理数据。
index.wxml
<!--index.wxml-->
<canvas canvas-id='canvas1' style='width: {{ww}}px;height: {{hh}}px;'></canvas>
index.js
const app = getApp()
const ctx = wx.createCanvasContext('canvas1')
const ww = app.globalData.ww
const hh = app.globalData.hh
Page({
data: {
ww: ww,
hh: hh
},
onLoad() {
var that = this;
wx.startAccelerometer({
success(res) {
that.start()
}
});
this.hf_w = ww / 2;
this.hf_h = hh / 2;
this.x = 0;
this.y = 0;
this.ax = 0;
this.ay = 0;
this.vx = 0;
this.vy = 0;
this.draw();
},
start() {
var vt = 5, that = this;
wx.onAccelerometerChange(function (res) {
that.ax = res.x * vt;
that.ay = res.y * vt;
});
setInterval(function () {
var lo = ww / hh > 1;
if (lo) {
that.vx = that.vx + that.ay;
that.vy = that.vy + that.ax;
} else {
that.vy = that.vy - that.ay;
that.vx = that.vx + that.ax;
}
that.vx = that.vx * 0.98;
that.vy = that.vy * 0.98;
that.y = parseInt(that.y + that.vy / 50);
that.x = parseInt(that.x + that.vx / 50);
that.boundingBoxCheck();
that.draw();
}, 100 / 6)
},
end() {
wx.stopAccelerometer()
},
draw() {
console.log(this.x);
ctx.clearRect(0, 0, ww, hh);
ctx.fillRect(0, 0, ww, hh)
ctx.fill()
ctx.beginPath();
ctx.arc(this.x, this.y, 20, 0, Math.PI * 2);
ctx.setFillStyle('#FFFFFF');
ctx.fill()
ctx.draw();
},
boundingBoxCheck() {
if (this.x < 0) { this.x = 0; this.vx = -this.vx; }
if (this.y < 0) { this.y = 0; this.vy = -this.vy; }
if (this.x > ww - 20) { this.x = ww - 20; this.vx = -this.vx; }
if (this.y > hh - 20) { this.y = hh - 20; this.vy = -this.vy; }
}
})
app.js
App({
onLaunch: function () {
var that = this;
wx.getSystemInfo({
success(res) {
that.globalData.ww = res.windowWidth;
that.globalData.hh = res.windowHeight;
}
})
},
globalData: {
userInfo: null
}
})
在canvas中绘制了一个小球,根据手机的倾斜小球在屏幕上滚动,碰触到边沿则回弹。
具体效果有兴趣的下载demo自己玩玩吧,过段时间准备拓展一下改成一个小游戏。