$(document).ready(function() { var canvas = $("#myCanvas").get(0); var context = canvas.getContext("2d"); var size = 50; var up = 90, right = 0, down = 270, left = 180; var direction = right; var speed = 10; var startAngle = 0.25; var endAngle = 1.75; var gapClosing = true; var posX, posY; switch (direction) { case up: posX = 75; posY = 500; break; case down: posX = 75; posY = 0; break; case left: posX = 500; posY = 75; break; case right: posX = 0; posY = 75; break; } function renderGrid(gridPixelSize, color) { context.save(); context.lineWidth = 0.5; context.strokeStyle = color; // horizontal grid lines for (var i = 0; i <= canvas.height; i = i + gridPixelSize) { context.beginPath(); context.moveTo(0, i); context.lineTo(canvas.width, i); context.closePath(); context.stroke(); } // vertical grid lines for (var j = 0; j <= canvas.width; j = j + gridPixelSize) { context.beginPath(); context.moveTo(j, 0); context.lineTo(j, canvas.height); context.closePath(); context.stroke(); } context.restore(); } function setAngles() { if (startAngle <= 0) gapClosing = true; else if (startAngle > 0.25) gapClosing = false; if (gapClosing) { startAngle = startAngle + 0.05; endAngle = endAngle - 0.05; } else { startAngle = startAngle - 0.05; endAngle = endAngle + 0.05; } } function renderContent() { context.save(); renderGrid(20, "red") context.beginPath(); context.fillStyle = "Yellow"; context.strokeStyle = "Yellow"; context.save(); context.translate(posX, posY); context.rotate(-direction * Math.PI / 180); context.translate(-posX, -posY); context.arc(posX, posY, size, (startAngle) * Math.PI, (endAngle) * Math.PI); context.lineTo(posX, posY); context.stroke(); context.fill(); context.restore(); context.restore(); } function animationLoop() { canvas.width = canvas.width; renderContent(); setAngles(); switch (direction) { case up: posY -= speed; if (posY <= 0) direction = down; break; case down: posY += speed; if (posY > 500) direction = up; break; case left: posX -= speed; if (posX < 0) direction = right; break; case right: posX += speed; if (posX > 500) direction = left; break; } setTimeout(animationLoop, 33); } animationLoop(); $("#up").click(function() { direction = up; }); $("#down").click(function() { direction = down; }); $("#left").click(function() { direction = left; }); $("#right").click(function() { direction = right; }); });
<canvas id="myCanvas" width="500" height="500"> <p>Canvas not supported.</p> </canvas> <input type="button" id="up" value="Up"/> <input type="button" id="down" value="Down"/> <input type="button" id="left" value="Left"/> <input type="button" id="right" value="Right"/>
* { margin: 0; padding: 0; } html, body { height: 100%; width: 100%; background-color: #000; } canvas { display: block; } #up, #down, #left, #right { position: absolute; padding: 2px; } #up { top: 420px; left: 30px; } #left { top: 445px; left: 12px; } #right { top: 445px; left: 45px; } #down { top: 470px; left: 25px; }