标签:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>canvas绘制钟表</title>
<style type="text/css">
#canvas{
/*border: 2px solid red;*/
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
</body>
<script type="text/javascript">
var canvas=document.getElementById(‘canvas‘);
var ctx=canvas.getContext(‘2d‘);
//通过平移和旋转改变画笔的原始坐标位置和X轴和Y轴的方向
ctx.translate(300,300);
ctx.rotate(-Math.PI/2);//逆时针旋转90度
//绘制表盘
function drawDial () {
//外层圆
ctx.beginPath();
ctx.arc(0,0,300,0,Math.PI*2,false);
ctx.fillStyle=‘gold‘;
ctx.fill();
//内层圆
ctx.beginPath();
ctx.arc(0,0,280,0,Math.PI*2,false);
ctx.fillStyle=‘white‘;
ctx.fill();
}
//绘制刻度 时刻和分刻
function drawScale () {
for (var i=0;i<60;i++) {
if (i%5==0) {
//绘制时刻 整点
ctx.beginPath();
ctx.moveTo(250,0);
ctx.lineTo(270,0);
ctx.lineWidth=10;
ctx.strokeStyle=‘black‘;
ctx.stroke();
}else{
//绘制分刻 非整点
ctx.beginPath();
ctx.moveTo(255,0);
ctx.lineTo(270,0);
ctx.lineWidth=7;
ctx.strokeStyle=‘gray‘;
ctx.stroke();
}
//旋转6度
ctx.rotate(Math.PI/180*6);
}
}
//绘制时针,分针,秒针
function drawTime () {
var time=new Date();
var hour=time.getHours();//时
var minute=time.getMinutes();//分
var second=time.getSeconds();//秒
//调用save函数,保存当前的绘制状态
ctx.save();
//需要旋转角度(坐标轴)
ctx.rotate(Math.PI/180*30*hour+
Math.PI/180*minute
/60*30);
//绘制时针
ctx.beginPath();
ctx.moveTo(-20,0);
ctx.lineTo(180,0);
ctx.lineWidth=13;
ctx.strokeStyle=‘black‘;
ctx.stroke();
//调用restore函数 移除自上一次调用save方法以来所添加的任何效果;也就是撤销之前的变化
ctx.restore();
//分针
ctx.save();
//旋转角度
ctx.rotate(Math.PI/
180*6*minute+Math.PI/180*
second/60*6);
//绘制分针
ctx.beginPath();
ctx.moveTo(-30,0);
ctx.lineTo(210,0);
ctx.lineWidth=8;
ctx.strokeStyle=‘black‘;
ctx.stroke();
ctx.restore();
//秒针
ctx.save();
ctx.rotate(Math.PI/180*6*second);
ctx.beginPath();
ctx.moveTo(-40,0);
ctx.lineTo(260,0);
ctx.strokeStyle=‘red‘;
ctx.lineWidth=3;
ctx.stroke();
ctx.restore();
//圆心点
ctx.beginPath();
ctx.arc(0,0,15,0,Math.PI*2,false);
ctx.fillStyle=‘rgba(150,100,200,0.5)‘;
ctx.fill();
}
//绘制钟表
function drawClock () {
drawDial();
drawScale();
drawTime();
//根据刷新频率,调用方法
window.requestAnimationFrame(drawClock);
}
drawClock();
</script>
</html>
标签:
原文地址:http://www.cnblogs.com/li-deblog/p/5914528.html