作者:手机用户2502862133 | 来源:互联网 | 2020-07-17 00:31
用HTML5 Canvas 制作的时钟,看着挺简单的,但其中写起来还是有很多小的问题的,感兴趣的小伙伴们可以参考一下
HTML5 时钟
[Javascript]代码
// inner variables
var canvas, ctx;
var clockRadius = 250;
var clockImage;
// draw functions :
function clear() { // clear canvas function
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function drawScene() { // main drawScene function
clear(); // clear canvas
// get current time
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var secOnds= date.getSeconds();
hours = hours > 12 ? hours - 12 : hours;
var hour = hours + minutes / 60;
var minute = minutes + seconds / 60;
// save current context
ctx.save();
// draw clock image (as background)
ctx.drawImage(clockImage, 0, 0, 500, 500);
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.beginPath();
// draw numbers
ctx.fOnt= '36px Arial';
ctx.fillStyle = '#000';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (var n = 1; n <= 12; n++) {
var theta = (n - 3) * (Math.PI * 2) / 12;
var x = clockRadius * 0.7 * Math.cos(theta);
var y = clockRadius * 0.7 * Math.sin(theta);
ctx.fillText(n, x, y);
}
// draw hour
ctx.save();
var theta = (hour - 3) * 2 * Math.PI / 12;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -5);
ctx.lineTo(-15, 5);
ctx.lineTo(clockRadius * 0.5, 1);
ctx.lineTo(clockRadius * 0.5, -1);
ctx.fill();
ctx.restore();
// draw minute
ctx.save();
var theta = (minute - 15) * 2 * Math.PI / 60;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -4);
ctx.lineTo(-15, 4);
ctx.lineTo(clockRadius * 0.8, 1);
ctx.lineTo(clockRadius * 0.8, -1);
ctx.fill();
ctx.restore();
// draw second
ctx.save();
var theta = (seconds - 15) * 2 * Math.PI / 60;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -3);
ctx.lineTo(-15, 3);
ctx.lineTo(clockRadius * 0.9, 1);
ctx.lineTo(clockRadius * 0.9, -1);
ctx.fillStyle = &#39;#0f0&#39;;
ctx.fill();
ctx.restore();
ctx.restore();
}
// initialization
$(function(){
canvas = document.getElementById(&#39;canvas&#39;);
ctx = canvas.getContext(&#39;2d&#39;);
// var width = canvas.width;
// var height = canvas.height;
clockImage = new Image();
clockImage.src = &#39;http://static.oschina.net/uploads/space/2012/0712/125855_nnla_89964.png&#39;;
setInterval(drawScene, 1000); // loop drawScene
});
以上就是介绍一个用HTML5 Canvas 制作的时钟的详细内容,更多请关注 第一PHP社区 其它相关文章!