Move the background image according to the tilt of the smartphoneDo you have a JavaScript library?

Asked 1 years ago, Updated 1 years ago, 36 views

I'm sorry for the direct link, but when I access the following site with a smartphone such as iPhone, the background image moves slowly according to the tilt of the smartphone.

http://ignition.co/104

Are these effects realized in jQuery or in some kind of library? Please let me know if anyone knows such a library.

javascript

2022-09-30 20:26

2 Answers

You can use the deviceoration event.

window.addEventListener('device orientation', function(e){
  // Get slope with e.alpha, e.beta, e.gamma
});

There is a detailed description of the MDN.

https://developer.mozilla.org/ja/docs/Detecting_device_orientation https://developer.mozilla.org/ja/docs/DOM/Orientation_and_motion_data_explained

The site mentioned in the question seems to be using the device event, but I've never used it before, so I don't know the details. https://developer.apple.com/library/iad/documentation/SafariDOMAdditions/Reference/DeviceMotionEventClassRef/DeviceMotionEvent/DeviceMotionEvent.html


2022-09-30 20:26

parallax.js
As ISHITOYA Kentaro commented, there is a library called parallax.js. Internally, it seems that you are using DeviceOrientationEvent. Official site

html5rocks
Also, there is a sample in html 5rocks.This also uses DeviceOrientationEvent. Sample

Browser Compatibility
DeviceOrientationEvent requires attention to browser compatibility, such as different behavior between Firefox and Chrome. MDN

DeviceOrientationEvent has three values, depending on the coordinate axis.

x-axis: beta degrees [-180-180]
y-axis: gamma degree [-90-90]
z-axis: alpha degree [0-360]

Also, the processing flow is as follows:

(1) Pick up DeviceOrientationEvent events
(2) Obtain tilt values for X, Y, and Z axes
(3) Adjust coordinate values to their preferred values
(4) Adjust the image position

In order to understand how it works, if you write only the skeleton in a few lines, it looks like the following:

 if(window.DeviceOrientationEvent){
    // (1) Pick up DeviceOrientationEvent events
    window.addEventListener("deviceoration", function(){
        // (2) Obtain the slope values of the X and Y axes.
        varx = Math.round (event.beta||0); // [-90,90]
        variable = Math.round (event.gamma||0); // [-180,180)

        // (3) Adjust the coordinate value to the desired value (omitted)

        // (4) Adjust the position of the image
        $('#contentarea') .css({'background-position-x':x,
                               'background-position-y':y});
    }, true);
} else {
  // DeviceOrientationEvent is not supported
}

jsfiddle source code
For checking jsfiddle operation

That's all.I hope it will be helpful.


2022-09-30 20:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.