JSFiddle - React, Tailwind, and code Playground
by Andrew Gerst
HTML
<canvas id="canvas" width=300 height=300></canvas>
CSS
body {
background-color: ivory;
}
canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var dd = 3;
var angle = 0;
var cx = 200;
var cy = 75;
var radius = 40;
ctx.fillStyle = "skyblue";
ctx.strokeStyle = "lightgray";
function draw(x, y) {
ctx.clearRect(0, 0, w, h);
ctx.save();
ctx.beginPath();
ctx.beginPath();
ctx.rect(x - 50 / 2, y - 30 / 2, 50, 30)
ctx.fill();
ctx.stroke();
ctx.restore();
};
var fps = 60;
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / fps);
};
})();
function animate() {
setTimeout(function () {
requestAnimFrame(animate);
// increase the angle of rotation
angle += Math.acos(1-Math.pow(dd/radius,2)/2);
// calculate the new ball.x / ball.y
var newX = cx + radius * Math.cos(angle);
var newY = cy + radius * Math.sin(angle);
// draw
draw(newX, newY);
// draw the centerpoint
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.stroke();
}, 1000 / fps);
}
animate();