Smooth element translate on device orientation change

336 Views Asked by At

I'm trying to achieve this sort of effect, but by using JS and on device orientation change (with gyroscope). So I wrote this code:

var sky, flag, objects, maxPositiveTranslateFar = 30, maxPositiveTranslateNear = 20, maxNegativeTranslateFar=-30, maxNegativeTranslateNear=-20;
document.addEventListener("DOMContentLoaded",onload); 
function onload(){
    sky = document.getElementById('sky');
    flag = document.getElementById('flag');
    objects = [{objectName : sky}, {objectName : flag}];

    if (window.DeviceOrientationEvent) {
        window.addEventListener('deviceorientation', function(eventData){
            var tiltLR = eventData.gamma;
            var tiltD = eventData.beta;
            deviceOrientationHandler(tiltLR, tiltD);
        }, false);
    } else {
        // Do something
    }
}

function deviceOrientationHandler(tiltLR, tiltD) {
    for(var i = 0; i <= objects.length - 1; i++){
        if(objects[i].objectName == flag){
            if(tiltLR > maxPositiveTranslateNear){
                tiltLR = maxPositiveTranslateNear;
            } else if(tiltLR < maxNegativeTranslateNear) {
                tiltLR = maxNegativeTranslateNear;
            }
            flag.style.webkitTransform = "translateX("+tiltLR+"px)";
        } else {
            if(tiltLR*1.7 > maxPositiveTranslateFar){
                tiltLR = maxPositiveTranslateFar;
            } else if(tiltLR*1.7 < maxNegativeTranslateFar) {
                tiltLR = maxNegativeTranslateFar;
            }
            if(tiltD > maxPositiveTranslateNear){
                tiltD = maxPositiveTranslateNear;
            } else if(tiltD < maxNegativeTranslateNear) {
                tiltD = maxNegativeTranslateNear;
            }
            sky.style.webkitTransform = "translateX("+(tiltLR*1.7)+"px) translateY("+tiltD+"px)";
        }
    }
}

It works, the sky and flag elements are moving correspondingly, however the movement isn't smooth as in the example above. I guess it's because the values are constantly changing when the device is rotated, thus the deviceorientationevent keeps firing. I tried to add transition to these elements' CSS:

-webkit-transition: -webkit-transform 1s ease-out;

But it just made things worse - the transform became really jumpy.

Does anybody have a solution how to make this transformation smooth? I have to do it with plain JS/CSS only, no external JS libraries (or by using a library, but it must very light-weight, 40-50 kb. is the max).

0

There are 0 best solutions below