<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
div{
text-align: center;
margin-top: 250px;
}
#click{
border: 1px solid #CCCCCC;
}
</style>
</head>
<body>
<div>
<canvas id="click" width="300px" height="300px"></canvas>
</div>
<script>
var canvas=document.getElementById('click');
var ctx=canvas.getContext('2d');
var w=ctx.canvas.width;
var h=ctx.canvas.height;
var r=w/2;
function drawCircle(){
ctx.save();
ctx.translate(r,r);
ctx.beginPath();
ctx.lineWidth=10;
ctx.arc(0,0,r-5,0,2*Math.PI,false);
ctx.stroke();
var hoursNum=[3,4,5,6,7,8,9,10,11,12,1,2];
hoursNum.forEach(function(number,i){
ctx.font='18px 微软雅黑';
ctx.textAlign='center';
ctx.textBaseline='middle';
var rad=2*Math.PI/12*i;
var y=(r-30)*Math.sin(rad);
var x=(r-30)*Math.cos(rad);
ctx.fillText(number,x,y);
})
}
function drawDots(){
for(j=0;j<60;j++){
ctx.beginPath();
var rad=2*Math.PI/60*j;
var y=(r-15)*Math.sin(rad);
var x=(r-15)*Math.cos(rad);
ctx.beginPath();
if(j%5===0){
ctx.fillStyle='#000'
ctx.arc(x,y,3,0,2*Math.PI,false);
}else{
ctx.fillStyle='#CCC';
ctx.arc(x,y,2,0,2*Math.PI,false);
}
ctx.fill();
}
ctx.beginPath();
ctx.fillStyle='white';
ctx.arc(0,0,2.5,0,2*Math.PI,false);
ctx.fill();
}
function drawHour(h,min){
ctx.save();
ctx.beginPath();
ctx.lineWidth=6;
ctx.lineCap='round';
var rad=2*Math.PI/12*h;
var minRad=2*Math.PI/720*min;
ctx.rotate(rad+minRad);
ctx.moveTo(0,10);
ctx.lineTo(0,-(r-50));
ctx.stroke();
ctx.restore();
}
function drawMinute(min,sec){
ctx.save();
ctx.beginPath();
ctx.lineWidth=4.5;
ctx.lineCap='round';
var rad=2*Math.PI/60*min;
var secRad=2*Math.PI/3600*sec;
ctx.rotate(rad+secRad);
ctx.moveTo(0,10);
ctx.lineTo(0,-(r-40));
ctx.stroke();
ctx.restore();
}
function drawSecond(sec){
ctx.save();
ctx.beginPath();
ctx.fillStyle='crimson';
ctx.rotate(2*Math.PI/60*sec);
ctx.moveTo(-2,20);
ctx.lineTo(2,20);
ctx.lineTo(1,-r+18);
ctx.lineTo(-1,-r+18);
ctx.fill();
ctx.restore();
}
function draw(){
var now=new Date();
var h=now.getHours();
var min=now.getMinutes();
var sec=now.getSeconds();
drawCircle();
drawHour(h,min);
drawMinute(min,sec);
drawSecond(sec);
drawDots();
ctx.restore();
}
draw();
setInterval(function(){
ctx.clearRect(0,0,w,h);
draw();
},1000);
</script>
</body>
</html>
用canvas画一个时钟
最新推荐文章于 2022-05-11 19:24:55 发布