2015-11-12 40 views

回答

3

當然可以。您從devicemotion事件獲得的加速度爲m /s²。

var lastTimestamp; 
var speedX = 0, speedY = 0, speedZ = 0; 
window.addEventListener('devicemotion', function(event) { 
    var currentTime = new Date().getTime(); 
    if (lastTimestamp === undefined) { 
    lastTimestamp = new Date().getTime(); 
    return; //ignore first call, we need a reference time 
    } 
    // m/s²/1000 * (miliseconds - miliseconds)/1000 /3600 => km/h (if I didn't made a mistake) 
    speedX += event.acceleration.x/1000 * ((currentTime - lastTimestamp)/1000)/3600; 
    //... same for Y and Z 
    lastTimestamp = currentTime; 
}, false); 

應該這樣做。但我會小心,因爲手機中的加速度計不太準確;)