<!DOCTYPE html> <html lang="jp" xml:lang="jp"> <head> <meta charset="utf-8"> <title>Balls</title> <style> .ball { position: absolute; top: 0px; left: 0px; } </style> <meta name="viewport" content="width=device-width,user-scalable=no" /> </head> <body> <header> <h1>Balls</h1> </header> <select onchange="selectBall(this);" id="bcolor" style="font-size:x-large;"> <option value="red" selected="selected">Red</option> <option value="green">Green</option> </select><br /> <canvas class="ball" id="red" width="20" height="20"></canvas> <canvas class="ball" id="green" width="20" height="20"></canvas> </body> <script type="text/javascript"> var myballColor = "red"; function selectBall(selectObj) { var idx = selectObj.selectedIndex; var ballColor = selectObj.options[idx].value; myballColor = ballColor; } var balls = document.getElementsByClassName("ball"); for(var i = 0; i < balls.length; i++) { var cv = document.getElementById(balls[i].id); var ctx = cv.getContext("2d"); ctx.fillStyle = balls[i].id; ctx.arc(10, 10, 10, 0, Math.PI * 2, true); ctx.fill(); } var ws = new WebSocket("ws://192.168.254.23:8888/balls"); ws.onopen = function() {}; ws.onmessage = function (evt) { var rdata = JSON.parse(evt.data); var ball = document.getElementById(rdata.ball); ball.style.top = rdata.y + "px"; ball.style.left = rdata.x + "px"; }; // Position Variables var x = 0; var y = 0; // Speed - Velocity var vx = 0; var vy = 0; // Acceleration var ax = 0; var ay = 0; var delay = 1000; // msec var vMultiplier = 1; window.addEventListener("devicemotion", function(evt) { ax = evt.accelerationIncludingGravity.x; ay = evt.accelerationIncludingGravity.y; }, true); setInterval(function() { vy = vy + -(ay); vx = vx + ax; var ball = document.getElementById(myballColor); y = parseInt(y + vy * vMultiplier); x = parseInt(x + vx * vMultiplier); if (x < 0) { x = 0; vx = 0; } if (y < 0) { y = 0; vy = 0; } if (x > document.documentElement.clientWidth - 20) { x = document.documentElement.clientWidth - 20; vx = 0; } if (y > document.documentElement.clientHeight - 20) { y = document.documentElement.clientHeight - 20; vy = 0; } ball.style.top = y + "px"; ball.style.left = x + "px"; ws.send(JSON.stringify({ball:myballColor, x:x, y:y})); }, delay); </script> </html>