版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36282409/article/details/83931120
<canvas id="clock" width="500" height="500" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。</canvas>
</div>
<script type="text/javascript">
var clock=document.getElementById("clock");
var c=clock.getContext("2d");
draw();
//自定义一个画图的函数
function draw(){
//清理画布
c.clearRect(0,0,500,500);
//获取当前时间
var now=new Date();
//获取当前秒钟数
var sec=now.getSeconds();
//获取当前分钟数
var min=now.getMinutes();
//获取小时数
var hours=now.getHours();
//当前的分钟占整个60分钟的小数是多少。
hours=hours+min/60;
// console.log(hours);
//把二十四小时转成十二小时制
hours=(hours>12?hours-12:hours);
//画表盘
c.beginPath();
c.lineWidth=10;
c.strokeStyle="#abc";
c.arc(250,250,200,0,2*Math.PI);
c.closePath();
c.stroke();
//小时
for(var i=0;i<12;i++){
c.save();
c.lineWidth=7;
c.strokeStyle="black";
//把中心点移动画布中间
c.translate(250,250);
c.rotate(i*30*Math.PI/180);
c.beginPath();
c.moveTo(0,-170);
c.lineTo(0,-190);
c.stroke();
c.closePath();
c.restore();
}
// 分钟
for(var i=0;i<60;i++){
c.save();
c.lineWidth=5;
c.strokeStyle="black";
c.translate(250,250);
c.rotate(i*6*Math.PI/180);
c.beginPath();
c.moveTo(0,-180);
c.lineTo(0,-190);
c.stroke();
c.closePath();
c.restore();
}
//时针
c.save();
c.lineWidth=10;
c.strokeStyle="black";
c.translate(250,250);
c.rotate(hours*30*Math.PI/180);
c.beginPath();
c.moveTo(0,-120);
c.lineTo(0,10);
c.stroke();
c.closePath();
c.restore();
//分针
c.save();
c.lineWidth=5;
c.strokeStyle="black";
c.translate(250,250);
c.rotate(min*6*Math.PI/180);
c.beginPath();
c.moveTo(0,-160);
c.lineTo(0,10);
c.stroke();
c.closePath();
c.restore();
//秒针
c.save();
c.lineWidth=3;
c.strokeStyle="red";
c.translate(250,250);
c.rotate(sec*6*Math.PI/180);
c.beginPath();
c.moveTo(0,-160);
c.lineTo(0,10);
c.stroke();
c.closePath();
c.restore();
//中间小圆点
c.arc(250,250,5,0,2*Math.PI);
c.fillStyle="red";
c.fill();
}
setInterval(draw,1000);
// alert(draw);
</script>