p5.js deviceMoved()函数
函数deviceMoved()在设备中工作,当设备沿所有三个 X、Y 或 Z 轴移动超过阈值时调用它。
它仅适用于手机等设备,它有助于检测设备何时移动或旋转超过阈值。
它可以用作移动设备中的传感器,例如检测运动、加速度、旋转、航向和位置。
默认阈值设置为0.5 ,可以使用setMoveThreshold()函数更改。
句法:
deviceMoved()
现在我们将在安卓手机上运行一些示例。
第一步:在手机中使用任意浏览器“https://editor.p5js.org/”打开p5.js的在线网页编辑器
第 2 步:在编辑器部分编写以下代码并运行它以查看输出。
示例 1:
Javascript
// Set value to zero
let value = 0;
// Set the draw function
function draw() {
// When the device is moved
// in the all direction then
// the colour fill filled
fill(value);
// Set the shape of thr Graphics
triangle(45, 100, 54, 5, 100, 100);
}
// Apply the deviceMoved function
function deviceMoved() {
// Increment the value everytime by 10
value = value + 10;
// If the value become greater than 255
// then reset the value to zero.
if (value > 255) {
value = 0;
}
}
Javascript
// Set the variable as 0
var value = 0;
// Set the function
function setup() {
createCanvas(windowWidth, windowHeight);
// Set the background as value which
// will be dynamic
background(value);
}
// Set the draw function
function draw() {
// Set the properties of text
background(value);
fill(0, 0, 255);
textAlign(CENTER, CENTER);
textSize(25);
// Set the limit for value
value = constrain(value - 2, 0, 200)
// If the value is greater than 10
if (value > 10) {
text("Moving Device", width / 2, height / 2);
} else {
text("Device is Relaxed ", width / 2, height / 2);
}
}
function deviceMoved() {
// Now increase the value.
value = constrain(value + 5, 0, 255)
}
输出:
示例 2:
Javascript
// Set the variable as 0
var value = 0;
// Set the function
function setup() {
createCanvas(windowWidth, windowHeight);
// Set the background as value which
// will be dynamic
background(value);
}
// Set the draw function
function draw() {
// Set the properties of text
background(value);
fill(0, 0, 255);
textAlign(CENTER, CENTER);
textSize(25);
// Set the limit for value
value = constrain(value - 2, 0, 200)
// If the value is greater than 10
if (value > 10) {
text("Moving Device", width / 2, height / 2);
} else {
text("Device is Relaxed ", width / 2, height / 2);
}
}
function deviceMoved() {
// Now increase the value.
value = constrain(value + 5, 0, 255)
}
输出: