Skip to content

Instantly share code, notes, and snippets.

@stonyw
Last active March 9, 2016 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stonyw/1fc9b74055467c519190 to your computer and use it in GitHub Desktop.
Save stonyw/1fc9b74055467c519190 to your computer and use it in GitHub Desktop.
A clock made by html canvas animation
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function drawArc(myArc, context) {
context.beginPath();
if (myArc.end - myArc.start < 360) {
context.moveTo(myArc.cx, myArc.cy);
}
context.arc(myArc.cx, myArc.cy, myArc.r, (myArc.start - 90) * Math.PI / 180, (myArc.end - 90) * Math.PI / 180, false);
if (myArc.end - myArc.start < 360) {
context.lineTo(myArc.cx, myArc.cy);
}
context.fillStyle = myArc.fillColor;
context.fill();
context.lineWidth = myArc.borderWidth;
context.strokeStyle = myArc.strokeColor;
context.stroke();
}
function animate(inner, outter, canvas, context, startTime) {
// update
var now = new Date();
var hh = now.getHours();
var mm = now.getMinutes();
var ss = now.getSeconds();
if (hh >= 6 && hh < 18) {
inner.fillColor = 'lightGrey';
} else {
inner.fillColor = 'grey';
}
inner.start = (hh % 12) * 30 + mm / 2;
inner.end = mm * 6;
if (ss != 0) {
outter.end = ss * 6;
} else {
outter.end = 360;
}
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
drawArc(outter, context);
drawArc(inner, context);
// request new frame
requestAnimFrame(function() {
animate(inner, outter, canvas, context, startTime);
});
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var now = new Date();
var inner = {
cx: 200,
cy: 200,
r: 60,
borderWidth: 1,
start: 0,
end: Math.PI * now.getMinutes() * 6 / 180,
fillColor: 'grey',
strokeColor: '#003300'
};
var outter = {
cx: 200,
cy: 200,
r: 75,
borderWidth: 1,
start: 0,
end: Math.PI * now.getSeconds() * 6 / 180,
fillColor: 'darkGrey',
strokeColor: '#003300'
}
setTimeout(function() {
var startTime = (new Date()).getTime();
animate(inner, outter, canvas, context, startTime);
}, 0);
</script>
</body>
</html>
@stonyw
Copy link
Author

stonyw commented Mar 9, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment