Skip to content

Instantly share code, notes, and snippets.

@jamesoshea
Created April 22, 2018 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesoshea/55368de22ba714d0c82645c6e7bfb6df to your computer and use it in GitHub Desktop.
Save jamesoshea/55368de22ba714d0c82645c6e7bfb6df to your computer and use it in GitHub Desktop.
Simple device acceleration using Vue
<html>
<head>
<title>Welcome to the danger zone</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
text-align: center;
}
.danger-zone {
background-color: #EE3333;
color: #EEEEEE;
}
</style>
</head>
<body>
<div id="app" :class="divClasses">
<p>Current X acceleration: {{x}}</p>
<p>Current Y acceleration: {{y}}</p>
<p>Current Z acceleration: {{z}}</p>
<p>Maximum X acceleration: {{maxX}}</p>
<p>Maximum Y acceleration: {{maxY}}</p>
<p>Maximum Z acceleration: {{maxZ}}</p>
<button @click="clearMax">Reset</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
var app = new Vue({
el: '#app',
data: {
x: 0,
y: 0,
z: 0,
maxX: 0,
maxY: 0,
maxZ: 0,
dangerZone: false,
},
computed: {
divClasses() {
return {
'danger-zone': this.dangerZone,
}
},
},
methods: {
clearMax() {
this.maxX = 0;
this.maxY = 0;
this.maxZ = 0;
this.dangerZone = false;
},
},
mounted() {
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', (event) => {
const a = event.accelerationIncludingGravity;
this.x = `${a.x.toFixed(4)} m/s2`;
this.y = `${a.y.toFixed(4)} m/s2`;
this.z = `${a.z.toFixed(4)} m/s2`;
this.maxX = Math.abs(this.maxX) < Math.abs(a.x) ? a.x : this.maxX;
this.maxY = Math.abs(this.maxY) < Math.abs(a.y) ? a.y : this.maxY;
this.maxZ = Math.abs(this.maxZ) < Math.abs(a.z) ? a.z : this.maxZ;
if (Math.max(Math.abs(a.x), Math.abs(a.y), Math.abs(a.z)) > 20) {
this.dangerZone = true;
}
});
} else {
console.log('sad.')
}
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment