當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js deviceShaken()用法及代碼示例

deviceShaken()函數在設備總加速度變化accelerationX且accelerationY值大於閾值時調用。

默認閾值設置為 30,可以使用 setShakeThreshold() 函數更改。

它可以用作移動設備中的傳感器,例如檢測運動、加速度、旋轉、航向和位置。

用法:

deviceShaken()

現在我們將在安卓手機上運行一些示例。



  • 第一步:在手機上用任意瀏覽器打開p5.js的在線網頁編輯器“https://editor.p5js.org/”

  • 步驟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)
}

輸出:當我們搖動設備時,我們將得到輸出

範例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 grater than 255
    // then reset the value to zero.
    if (value > 255) {
        value = 0;
    }
}

輸出:

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




相關用法


注:本文由純淨天空篩選整理自_sh_pallavi大神的英文原創作品 p5.js deviceShaken() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。