Js:我的图像没有在我的ipad设备上移动

时间:2017-03-28 16:44:46

标签: javascript ipad accelerometer

我是Js开发人员的初学者。我使用加速度计来移动图像。我在这个website找到了一个教程。

我重写了它。但是当我移动我的iPad时,我试图移动我的图像,但我无法理解为什么。这是the link to my code on codepen.io。来自codepen的javascript代码如下:

"use strict";

//when the bom is loaded...
window.addEventListener("load", function followOrder(event) {
    //create a variable with getElementById for being reacted on the iOS devices movements
    let rabbit = document.getElementById('image');
    //variables for the position
    //the position of the image
    let posX = 0,
        posY = 0,
        //the speed of the bouncing
        spX = 0,
        spY = 0,
        //the acceleration of
        accX = 0,
        accY = 0;

    //make it bouncing in the edges of the screen
    let bouncingRabbit = function() {
        //IF posX and posY is superior to zero ...
        if (posX < 0 || posY < 0) {
            //...so posX is equal to zero
            posX = 0;
            posY = 0;
            //make the sp
            spX = -spX;
            spY = -spY;
        }
        if (posX > document.documentElement.clientWidth - 20 || posY > document.documentElement.clientHeight - 20) {

            posX = document.documentElement.clientWidth - 20;
            posY = document.documentElement.clientHeight - 20;

            spX = -spX;
            spY = -spY;
        }
    }

    let detectTheSensor = function(e) {
        //create three variables to include the accelerometer in 3d
        e.accelerationIncludingGravity.x;
        e.accelerationIncludingGravity.y;
        e.accelerationIncludingGravity.z;
        //return the amount of acceleration recorded by the device multiply by the speed of the move
        accX = e.accelerationIncludingGravity.x * 5;
        accY = e.accelerationIncludingGravity.y * 5;
    }

    //create a const variable to set an interval to move the image
    setInterval(function() {
        /*the landscapeOrientation divide the window.innerWidth & the window.innerHeight
        to get the size in px of the screen*/
        let landscapeOrientation = window.innerWidth / window.innerHeight > 1;
        if (landscapeOrientation) {
            //Calculate the screen surface
            spX = spX + accY;
            spY = spY + accX;
        } else {
            spY = spY - accY;
            spX = spX + accX;
        }
        //the speed of the bouncing
        spX = spX * 0.98;
        spY = spY * 0.98;
        //send back in integer the calculate
        posY = Math.round(posY + spY / 50);
        posX = Math.round(posX + spX / 50);
        //invoke the bouncingRabbit
        bouncingRabbit();
        //make move the object in css
        image.style.top = posX + "px";
        image.style.left = posY + "px";
    }, 15);

    //call the addEventListener to trigger the event devicemotion
    window.addEventListener("devicemotion", detectTheSensor);
});

0 个答案:

没有答案