JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id='myCanvas'></canvas>
<span></span>
JavaScript
position = [0.2, 0.2];
velocity = [0, 0];
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var radius = 1;
setInterval(function () {
if (window.DeviceMotionEvent != undefined) {
window.ondevicemotion = function(event) {
console.log(event);
x = event.accelerationIncludingGravity.x;
y = event.accelerationIncludingGravity.y;
z = event.accelerationIncludingGravity.z - 9.8065;
$("span").html("velocity: " + velocity[0] + ", " + velocity[1]);
}
}
velocity = [x / 1000, -y / 1000];
position = [position[0] + velocity[0], position[1] + velocity[1]];
if (position[0] > 1) {
position[0] = 1;
} else if (position[0] < 0) {
position[0] = 0;
}
if (position[1] > 1) {
position[1] = 1;
} else if (position[1] < 0) {
position[1] = 0;
}
context.beginPath();
context.arc(position[0] * canvas.width, position[1] * canvas.height, radius, 0, 2 * Math.PI, false);
context.lineWidth = 1;
context.strokeStyle = '#444';
context.stroke();
}, 20);