JSFiddle - React, Tailwind, and code Playground

by gkucmierz

HTML

<div></div>

CSS

div {
    position: absolute;
    background-color: #08f;
    width: 50px;
    height: 50px;
    border-radius: 25px;
}

JavaScript

var doc = {
    w: document.documentElement.clientWidth,
    h: document.documentElement.clientHeight
};
var ball = {
    ref: document.querySelector('div'),
    w: 50,
    h: 50,
    x: doc.w / 2 - 25,
    y: doc.h / 2 - 25,
    xs: 0,
    ys: 0
};
var friction = 0.995;

setInterval(function() {
    ball.x += ball.xs;
    ball.y += ball.ys;
    
    if ((ball.x <= 0 && ball.xs < 0) || (ball.x >= doc.w - ball.w && ball.xs > 0)) ball.xs *= -1;
    if ((ball.y <= 0 && ball.ys < 0) || (ball.y >= doc.h - ball.h && ball.ys > 0)) ball.ys *= -1;
    
    ball.xs *= friction;
    ball.ys *= friction;
    
    ball.ref.style.left = ball.x + 'px';
    ball.ref.style.top = ball.y + 'px';
}, 30);


window.ondevicemotion = function(e) {
    ball.xs += e.accelerationIncludingGravity.x * 0.2;
    ball.ys -= e.accelerationIncludingGravity.y * 0.2;
};