HTML5 canvas 指针时钟

时间:2023-03-09 20:37:31
HTML5 canvas 指针时钟
<!doctype html>
<html>
<head></head>
<body>
<canvas id="clock" width="" height="">
您的浏览器不支持canvas标签,无法看到时钟
</canvas>
<script>
var clock=document.getElementById('clock');
var cxt=clock.getContext('2d'); function drawClock(){
cxt.clearRect(,,,); //清除画布区域
var now =new Date();
var sec=now.getSeconds();
var min=now.getMinutes();
var hour=now.getHours(); hour=hour+min/; //小时必须获取浮点类型(小时+分数转化成的小时)
//问题 19:23:30
//将24小时进制转换为12小时
hour=hour>?hour-:hour; cxt.lineWidth=;
cxt.strokeStyle="#A61C3E"; //表盘(蓝色)
cxt.beginPath();
cxt.arc(,,,,Math.PI*,false);
cxt.closePath();
cxt.stroke(); //时刻度
for(var i=;i<;i++){
cxt.save();
cxt.lineWidth=; //设置时针的粗细
cxt.strokeStyle="#005693"; //设置时针的颜色
cxt.translate(,);
cxt.rotate(i**Math.PI/);//角度*Math.PI/180=弧度
cxt.beginPath();
cxt.moveTo(,-);
cxt.lineTo(,-);
cxt.closePath();
cxt.stroke();
cxt.restore();
} //分刻度
for(var i=;i<;i++){
cxt.save();
cxt.lineWidth=;
cxt.strokeStyle="#04562E";
cxt.translate(,);
cxt.rotate(i**Math.PI/);
cxt.beginPath();
cxt.moveTo(,-);
cxt.lineTo(,-);
cxt.closePath();
cxt.stroke();
cxt.restore();
} //时针
cxt.save();
cxt.lineWidth=;
cxt.strokeStyle="#04562E";
cxt.translate(,);//设置异次元空间的0,0点,画布的圆心
cxt.rotate(hour**Math.PI/);
cxt.beginPath();
cxt.moveTo(,-); //针长
cxt.lineTo(,);
cxt.closePath();
cxt.stroke();
cxt.restore(); //分针
cxt.save();
cxt.lineWidth=;
cxt.strokeStyle="#000";
cxt.translate(,);
cxt.rotate(min**Math.PI/);
cxt.beginPath();
cxt.moveTo(,-);
cxt.lineTo(,);
cxt.closePath();
cxt.stroke();
cxt.restore(); //秒针
cxt.save();
cxt.strokeStyle="#611123";
cxt.lineWidth=;
cxt.translate(,);
cxt.rotate(sec**Math.PI/);//设置旋转角度
cxt.beginPath(); //画图
cxt.moveTo(,-);
cxt.lineTo(,);
cxt.closePath();
cxt.stroke();
cxt.beginPath(); //画出时针、分针、秒针的交叉点、
cxt.arc(,,,,,false);
cxt.closePath();
cxt.fillStyle="gray"; //设置填充样式
cxt.fill();
cxt.stroke(); //设置秒针前段的小圆点
cxt.beginPath();
cxt.arc(,-,,,,false);
cxt.closePath();
cxt.fillStyle="#FFF";
cxt.fill();
cxt.stroke();//设置笔触样式(秒针已设置)
cxt.restore();
} drawClock(); //1000毫秒前要显示
//使用setInterval(代码,毫秒时间) 让时钟动起来
setInterval(drawClock,);
</script>
</body>
</html>