用canvas 做一个钟表

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
#box{
420px;
margin: 50px auto 0;

}
#cav{
background:#F2E7E7;
}
</style>
</head>
<body>
<div id="box">
<canvas id="cav" width="420" height="420"></canvas>
</div>
<script>
var cav=document.getElementById('cav');
var ctx=cav.getContext('2d');
clock();
setInterval(clock,1000);
function clock(){

var img=new Image();

img.src='../img/05.jpg';
ctx.beginPath();
ctx.drawImage(img,0,0,420,420);
ctx.closePath();

ctx.beginPath();
ctx.strokeStyle='#AC72A9';
ctx.lineWidth=10;
ctx.arc(210,210,200,0,2*Math.PI,true);
ctx.stroke();
ctx.closePath();
ctx.clip();
//要先画分钟的,再画小时的,让小时的覆盖住整点的那个
//分钟的刻度 每分钟转6deg
for (var i = 0; i < 60; i++) {
ctx.save();
ctx.translate(210,210);//把画布的原点移到圆的原点处
ctx.rotate(6*i*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,-185);
ctx.lineTo(0,-195);
ctx.closePath();
ctx.strokeStyle='#D859A1';
ctx.lineWidth=8;
ctx.stroke();
ctx.restore();
}
// 小时的刻度 ,每小时转30deg
for (var i = 0; i < 12; i++) {
ctx.save();
ctx.translate(210,210);//把画布的原点移到圆的原点处
ctx.rotate(30*i*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,-175);
ctx.lineTo(0,-195);
ctx.closePath();
ctx.strokeStyle='#29B2D9';
ctx.lineWidth=10;
ctx.stroke();
ctx.restore();
}
//获取当前时间
var dates=new Date();
var h=dates.getHours();
var m=dates.getMinutes();
var s=dates.getSeconds();
h=h+m/60;//当前的几点几小时
m=m+s/60;//当前是几点几分
//画时间
var h2=dates.getHours();
var m2=dates.getMinutes();
var str1=h2>9?h2:'0'+h2;
var str2=m2>9?m2:'0'+m2;
var str=str1+':'+str2;
ctx.beginPath();
ctx.fillStyle='#12B64E';
ctx.fillText(str,170,350);
ctx.font='bold 30px 微软雅黑';
ctx.closePath();

//时针
ctx.save();
ctx.translate(210,210);//把画布的原点移到圆的原点处
ctx.rotate(30*h*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,15);
ctx.lineTo(0,-130);
ctx.closePath();
ctx.strokeStyle='#29B2D9';
ctx.lineWidth=10;
ctx.stroke();
ctx.restore();
//分针
ctx.save();
ctx.translate(210,210);//把画布的原点移到圆的原点处
ctx.rotate(6*m*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,15);
ctx.lineTo(0,-150);
ctx.closePath();
ctx.strokeStyle='#D859A1';
ctx.lineWidth=5;
ctx.stroke();
ctx.restore();
//秒针
ctx.save();
ctx.translate(210,210);//把画布的原点移到圆的原点处
ctx.rotate(6*s*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,15);
ctx.lineTo(0,-170);
ctx.strokeStyle='#D01B5A';
ctx.lineWidth=3;
ctx.stroke();
ctx.closePath();
//秒针底部的圆圈
ctx.beginPath();
ctx.arc(0,0,8,0,2*Math.PI,true);
ctx.fillStyle='#D859A1';
ctx.strokeStyle='#D01B5A';
ctx.lineWidth=3;
ctx.stroke();
ctx.fill();
ctx.closePath();
//秒针顶部的圆
ctx.beginPath();
ctx.arc(0,-155,4,0,2*Math.PI,true);
ctx.fillStyle='#D859A1';
ctx.strokeStyle='#D01B5A';
ctx.lineWidth=3;
ctx.stroke();
ctx.fill();
ctx.closePath();
ctx.restore();

 

}
</script>
</body>
</html>

效果图:

原文地址:https://www.cnblogs.com/SunShineM/p/6001245.html