p5.js deviceShaken() Function
The function deviceShaken() function is called when the device total acceleration changes accelerationX and accelerationY values is more than the threshold value.
The default threshold is set to 30, and it can be changed using setShakeThreshold() function.
It can be used as a sensor in mobile devices like detecting motion, acceleration, rotation, heading, and location.
Syntax:
deviceShaken()
Now we will run some examples on android phones.
Step 1: Open online web editor of p5.js on the mobile phone using any browser “https://editor.p5js.org/”
Step 2: Write the following code in the editor section and run it to see the output.
Example 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) } |
Output: When we shake the device then we will get the output
Example 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; } } |
Output:
Reference: https://p5js.org/reference/#/p5/deviceShaken