📜  p5.js deviceShaken()函数

📅  最后修改于: 2022-05-13 01:56:50.834000             🧑  作者: Mango

p5.js deviceShaken()函数

当设备总加速度变化accelerationX和accelerationY值大于阈值时函数deviceShaken()函数。

默认阈值设置为 30,可以使用setShakeThreshold()函数更改。

它可以用作移动设备中的传感器,例如检测运动、加速度、旋转、航向和位置。

句法:

deviceShaken()

现在我们将在安卓手机上运行一些示例。

第一步:在手机上使用任意浏览器“https://editor.p5js.org/”打开p5.js的在线网页编辑器

第 2 步:在编辑器部分编写以下代码并运行它以查看输出。

示例 1:

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("Shaking Device", width / 2, height / 2);
    } else {
        text("Device is Silent ", width / 2, height / 2);
    }
}
 
function deviceShaken() {
 
    // Now increase the value.
    value = constrain(value + 5, 0, 255)
}


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
     rect(50, 50, 100, 100);
}
 
// Apply the deviceShaken function
function deviceShaken() {
 
    // 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;
    }
}


输出:当我们摇动设备时,我们将得到输出

示例 2:

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
     rect(50, 50, 100, 100);
}
 
// Apply the deviceShaken function
function deviceShaken() {
 
    // 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;
    }
}

输出:

参考: https://p5js.org/reference/#/p5/deviceShaken