一.html
<canvas id="clock" width="500" height="500" >你的浏览器不支持canvas</canvas>
二.css
canvas{
background: #000;
}
三.js
<script>
/*
难点1:怎样把时刻线绘制出来
难点2: 时间指针的旋转角度
秒:360/60是1秒的角度 每秒旋转6度数
分钟:
1小时是1圈 60分钟是1小时,每分钟是360/60. 每分钟旋转6度数
时钟: 12小时是一圈,一天24小时是2圈
360/12 30.1小时旋转30度,,小时为12的时候角度为0 .
分钟的整个角度需要加秒钟的角度
时钟的角度需要加分钟的角度比如:1:30 那么度数是30+15 45度
*/
var canvas = document.getElementById("clock");
var ctx = canvas.getContext("2d");
//-----------------------------秒针-----------------------------
setInterval(function () {
var now = new Date();
var sec = now.getSeconds();
var min = now.getMinutes();
min+=sec/60;
var hour = now.getHours();
hour > 12 ? hour - 12 : hour;
hour += (min / 60);
ctx.clearRect(0,0,500,500)
for (var i = 0; i < 12; i++) {
ctx.save();
ctx.translate(250, 250);
ctx.rotate(i*30*Math.PI/180)
ctx.beginPath();
ctx.moveTo(0,-175);
ctx.lineTo(0,-150);
ctx.lineWidth = 7;
ctx.strokeStyle = "pink"
ctx.stroke();
ctx.closePath();
ctx.restore();
}
// 秒钟
ctx.save();
ctx.lineWidth = 3;
ctx.strokeStyle = "#FF0000";
ctx.translate(250, 250);
ctx.rotate(sec * 6 * Math.PI / 180);//每秒旋转6度
ctx.beginPath();
ctx.moveTo(0, -170);
ctx.lineTo(0, 10);
ctx.stroke();
ctx.closePath();
ctx.restore();
// 分钟
ctx.save();
ctx.lineWidth = 6;
ctx.strokeStyle = "orange";
ctx.translate(250, 250);
ctx.rotate(min * 6 * Math.PI / 180);//每秒旋转6度
ctx.beginPath();
ctx.moveTo(0, -170);
ctx.lineTo(0, 10);
ctx.stroke();
ctx.closePath();
ctx.restore();
// 时钟
ctx.save();
ctx.lineWidth = 10;
ctx.strokeStyle = "blue";
ctx.translate(250, 250);
ctx.rotate(hour * 30 * Math.PI / 180);//每秒旋转6度
ctx.beginPath();
ctx.moveTo(0, -130);
ctx.lineTo(0, 10);
ctx.stroke();
ctx.closePath();
ctx.restore();
},1000)
</script>