<html>
<body>
<h2>Acceleration including gravity</h2>
<img src="../motion/axis.png">
<h2>
<a id="start" href="#" role="button" >Start</a> Graph Colours <font color="#cc0000">X </font> <font color="#006600">Y </font><font color="#3333ff">Z</font> </h2>
<canvas id="canvas" style="border: 1px solid" width="900" height="300">Whoops - can't do it</canvas>
<script>
var canvas = document.getElementById('canvas');
var ct = canvas.getContext('2d');
var raf;
var dpsx = [];
var dpsy = [];
var dpsz = [];
var width = 900;
var height = 300;
var interval = 5;
var scale = 5;
var num = width/interval;
var graph = {
xcolor: 'red',
ycolor: 'green',
zcolor: 'blue',
width: 1,
draw: function() {
ct.beginPath();
ct.moveTo(0,0);
ct.strokeStyle = this.xcolor;
ct.lineWidth = this.width;
for (let i=0; i < dpsx.length; i++){
let x = height/2 - scale*dpsx[i];
ct.lineTo(i * interval, x);
}
ct.stroke();
ct.beginPath();
ct.moveTo(0,0);
ct.strokeStyle = this.ycolor;
ct.lineWidth = this.width;
for (let i=0; i < dpsy.length; i++){
let y = height/2 - scale*dpsy[i];
ct.lineTo(i * interval, y);
}
ct.stroke();
ct.beginPath();
ct.moveTo(0,0);
ct.strokeStyle = this.zcolor;
ct.lineWidth = this.width;
for (let i=0; i < dpsz.length; i++){
let z = height/2 - scale*dpsz[i];
ct.lineTo(i * interval, z);
}
ct.stroke();
}
};
function draw() {
ct.clearRect(0, 0, width, height);
graph.draw();
raf = window.requestAnimationFrame(draw);
}
raf = window.requestAnimationFrame(draw);
graph.draw();
function updateIfNotNull(valName, value){
if (value != null) {
if(valName == 'X'){
dpsx.push(value);
if (dpsx.length >= num) {
dpsx.shift();
}
} else if (valName == 'Y') {
dpsy.push(value);
if (dpsy.length >= num) {
dpsy.shift();
}
} else if (valName == 'Z') {
dpsz.push(value);
if (dpsz.length >= num) {
dpsz.shift();
}
}
}
}
function handleMotion(event) {
updateIfNotNull('X', event.accelerationIncludingGravity.x);
updateIfNotNull('Y', event.accelerationIncludingGravity.y);
updateIfNotNull('Z', event.accelerationIncludingGravity.z);
}
let is_running = false;
let button = document.getElementById("start");
button.onclick = function(e) {
e.preventDefault();
if ( DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === "function") {
DeviceMotionEvent.requestPermission();
}
if (is_running){
window.removeEventListener("devicemotion", handleMotion);
button.innerHTML = "Start";
is_running = false;
}else{
window.addEventListener("devicemotion", handleMotion);
document.getElementById("start").innerHTML = "Stop";
is_running = true;
}
};
</script>
</body>
</html>