【项目描述】
本项目使用Canvas技术,完成了一个圆形时钟。具体效果如下。可用浏览器打开index.html文件,查看项目演示效果。
![5044877fc5605bb72713d9f03d073f61.png](https://i-blog.csdnimg.cn/blog_migrate/53970c9abd7e39d527f97424f0222bf3.png)
【练习知识点】
本项目练习的知识点如下所示:
l HTML5 Canvas
【项目分析】
本项目的结构构成非常简单,重点在于HTML5 Canvas的运用练习。页面结构图如下。
![b47d465abdd125fbfdb549f22f57bd36.png](https://i-blog.csdnimg.cn/blog_migrate/128eb010f22b655036c28bd88347ad37.png)
如图所示,整个页面是一个canvas标签构成的。 具体结构如下:
l 最外层粉色区域是外表盘。
l 红色虚线代表分钟刻度线。
l 黑色虚线代表时钟刻度线。
l 另外还需要绘制时针、分针和秒针。
【项目实现】
首先观察项目展示图,首选需要在HTML页面中添加<canvas>标签,然后使用JavaScript操作canvas来实现绘制步骤,主要步骤如下:
1. 获取画布对象,然后使用clearRect()方法对画布区域进行清除矩形操作。
2. 获取当前时间,转换互补坐标系为了让绘制的钟表完全显示,然后确定旋转点。
3. 绘制时钟刻度线。
4. 绘制分钟刻度线。
5. 绘制外表盘、时针、分针、秒针。
6. 使用定时器,每隔一秒钟重新调用绘制方法,达到表针转动的效果。
该项目的实现代码具体如下所示。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>html5 canvas圆形时钟</title>
<style type="text/css">
#myCanvas{
display: block;
margin:10px auto;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script type="text/javascript">
var myCanvas = document.getElementById('myCanvas');
var c = myCanvas.getContext('2d');
function clock(){
c.clearRect(0,0,400,400);
// 获取当前时间
var data = new Date();
var sec =data.getSeconds();//获取秒
var min =data.getMinutes();//获取小时
var hour=data.getHours();//获取分钟
c.save();//保存当前状态
c.translate(200,200);//转换画布坐标系统
c.rotate(Math.PI/2);//确定旋转点的
//分钟刻度线
for(var i=0;i<60;i++){ //画12个刻度线
c.beginPath();
c.strokeStyle = "#f00";
c.lineWidth = 5 ;
c.moveTo(117,0);
c.lineTo(120,0);
c.stroke();
c.rotate(Math.PI/30); //每个6deg画一个时钟刻度线
c.closePath();
}
//时钟刻度线
for(var i=0;i<12;i++){ //画12个刻度线
c.beginPath();
c.strokeStyle = "#000";
c.lineWidth = 8 ;
c.moveTo(100,0);
c.lineTo(120,0);
c.stroke();
c.rotate(Math.PI/6); //每个30deg画一个时钟刻度线
c.closePath();
}
//外表盘
c.beginPath();
c.strokeStyle = "pink";
c.arc(0,0,145,0,Math.PI*2);
c.lineWidth = 12 ;
c.stroke();
c.closePath();
//画时针
hour = hour>12?hour-12:hour;
c.beginPath();
c.save();
c.rotate(Math.PI/6*hour+Math.PI/6*min/60+Math.PI/6*sec/3600);
c.strokeStyle = "yellowgreen";
c.lineWidth = 4 ;
c.moveTo(-20,0);
c.lineTo(50,0);
c.stroke();
c.restore();
c.closePath();
//画分针
c.beginPath();
c.save();
c.rotate(Math.PI/30*min+Math.PI/30*sec/60);
c.strokeStyle = "springgreen";
c.lineWidth = 3 ;
c.moveTo(-30,0);
c.lineTo(70,0);
c.stroke();
c.restore();
c.closePath();
//画秒针
c.beginPath();
c.save();
c.rotate(Math.PI/30*sec);
c.strokeStyle = "red";
c.lineWidth = 2 ;
c.moveTo(-40,0);
c.lineTo(120,0);
c.stroke();
c.restore();
c.closePath();
c.restore();
}
clock();
setInterval(clock,1000);//定时器,每隔一秒重新绘制钟表
</script>
</body>
</html>