<!DOCTYPE HTML >
<html>
<head>
<title>Our Time!</title>
<meta http-equiv="content-type" content="text/html:charset=utf-8">
</head>
<body>
<canvas id="ourTime" width="10000" height="10000">很抱歉,您的浏览器不支持canvas标签!</canvas>
</body>
<script type="text/javascript">
var cs = document.getElementById("ourTime");
var ctx = cs.getContext("2d");
function ourTime() {
//每调用一次,清除一次画布
ctx.clearRect(0, 0, 10000, 10000);
//获取当前时间
var date = new Date();
var hour = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
//将24小时制转化为12小时制
var hours = hour + minutes / 60;
hours = hours > 12 ? hours - 12 : hours;
//显示当前时间
ctx.font="30px Courier New";
ctx.fillText("当前时间为:"+hour+":"+minutes+":"+seconds,100,400);
//绘制背景
ctx.fillStyle = "#ffffff";
ctx.strokeStyle = "#000";
ctx.lineWidth = 5;
ctx.beginPath();
ctx.arc(900, 450, 400, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
ctx.stroke();
//绘制时钟中心
ctx.fillStyle = "#000";
ctx.beginPath();
ctx.arc(900, 450, 10, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
//绘制刻度
//绘制时刻度
for (var h = 0; h < 12; h++) {
ctx.strokeStyle = "#000";
ctx.lineWidth = 3;
ctx.save();
ctx.translate(900, 450);
ctx.rotate(h * 30 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 360);//线段起点,离圆心的距离(相当于圆心为原点)
ctx.lineTo(0, 400);//线段终点
ctx.closePath();
ctx.stroke();
ctx.restore();
}
//绘制分刻度
for (var m = 0; m < 60; m++) {
ctx.strokeStyle = "#000";
ctx.lineWidth = 1;
ctx.save();
ctx.translate(900, 450);
ctx.rotate(m * 6 * Math.PI / 180);
ctx.beginPath();
ctx.moveTo(0, 380);
ctx.lineTo(0, 400);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
//绘制刻度值
ctx.font="30px Arial";
ctx.fillText("12",880,120);
ctx.fillText("11",710,170);
ctx.fillText("10",590,280);
ctx.fillText("9",550,460);
ctx.fillText("8",600,640);
ctx.fillText("7",720,755);
ctx.fillText("6",890,800);
ctx.fillText("5",1060,755);
ctx.fillText("4",1180,640);
ctx.fillText("3",1230,460);
ctx.fillText("2",1180,280);
ctx.fillText("1",1055,170);
//绘制指针
//绘制时针
ctx.strokeStyle = "#000";
ctx.lineWidth = 5;
ctx.save();
ctx.translate(900, 450);
ctx.rotate(hours*30*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0, -120);
ctx.lineTo(0, 25);
ctx.closePath();
ctx.stroke();
ctx.restore();
//绘制分针
ctx.strokeStyle = "#000";
ctx.lineWidth = 4;
ctx.save();
ctx.translate(900, 450);
ctx.rotate(minutes*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0, -250);
ctx.lineTo(0, 20);
ctx.closePath();
ctx.stroke();
ctx.restore();
//绘制秒针
ctx.strokeStyle = "#000";
ctx.lineWidth = 2;
ctx.save();
ctx.translate(900, 450);
ctx.rotate(seconds*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0, -300);
ctx.lineTo(0, 20);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
ourTime();
setInterval(ourTime,1000);
</script>
</html>
canvas 动画制作——时钟
最新推荐文章于 2023-10-31 22:59:28 发布