Change background image in mobile when device motion is changed

85 Views Asked by At

I am trying to change the background image when mobile device motion is changed (Like you make the device top, left or right, or up-down motion). i am using this code, issue is its start working immediately, even I don't change the motion of device by hand. its keep on updating always in a loop.

what I want when I change the mobile device a bit right or left or up down, it should change image than, any idea how I can make it working:

window.addEventListener("devicemotion", function(event){
        if(event.rotationRate.alpha || event.rotationRate.beta || event.rotationRate.gamma)
        {
            var myImages = new Array("victoria_bg.png", "victoria_bg_2.png", "victoria_bg_3.png", "victoria_bg_4.png");
            var random = myImages[Math.floor(Math.random() * myImages.length)];
            random = 'url(<?php echo base_url();?>resources/mobile/images/' + random + ')';
        } 
    });
1

There are 1 best solutions below

3
fdomn-m On

From MDN

The devicemotion event is fired at a regular interval

so it's not a traditional event like click but fires constantly. You'll need to store the previous event's values and compare to see if it's changed.

Due to how the alpha/beta/gamma are provided, you'll likely need some tolerance. Test the exact values being returned to determine how much tolerance/sensitivity is required in your scenario.

Here's an example:

var prevAlpha = 0.0;
var prevBeta = 0.0;
var prevGamma = 0.0;

window.addEventListener("devicemotion", function(event){
    if (event.rotationRate.alpha < (prevAlpha - 0.5) 
       || event.rotationRate.alpha > (prevAlpha + 0.5)
       || event.rotationRate.beta < (prevBeta - 0.5) 
       || event.rotationRate.beta > (prevBeta + 0.5)
       || event.rotationRate.gamma < (prevGamma - 0.5) 
       || event.rotationRate.gamma > (prevGamma + 0.5))
    {
        prevAlpha = event.rotationRate.alpha;
        prevBeta = event.rotationRate.beta;
        prevGamma = event.rotationRate.gamma;

        ... code to run on a change
    } 
});

(obviously can use an object / namespacing / scope to reduce global variables)