html5学习(一)--canvas画时钟

时间:2023-03-09 19:14:12
html5学习(一)--canvas画时钟
利用空余时间学习一下html5.
 <!doctype html>
<html>
<head></head>
<body>
<canvas id="clock" width="500" height="500"></canvas>
<script>
var clock=document.getElementById('clock');
var cxt = clock.getContext('2d');
function drawClock(){
//清除画布
cxt.clearRect(0,0,500,500);
var now = new Date();
var sec = now.getSeconds();
var min = now.getMinutes();
var hour = now.getHours();
//小时必须获取浮点类型(小时+分数转化成的小时);
hour= hour+min/60;
//问题:2014年8月18日 22:08:41
//将24小时进制转换成12小时
hour= hour>12?hour-12:hour;
//表盘(蓝色)
cxt.lineWidth=10;
cxt.strokeStyle="blue";
//刻度
cxt.beginPath();
cxt.arc(250,250,200,0,360,false);
cxt.closePath();
cxt.stroke();
//时刻度
for(var i=0;i<12;i++){
cxt.save();//保持当前状态
cxt.lineWidth=10;//设置时针的粗细
cxt.strokeStyle="#000";//设置时针颜色
cxt.translate(250,250);//设置0,0点
cxt.rotate(i*30*Math.PI/180);//设置旋转角度(=角度*Math*PI/180)
cxt.beginPath();
cxt.moveTo(0,-170);
cxt.lineTo(0,-190);
cxt.closePath();
cxt.stroke();
cxt.restore();//释放状态
}
//分刻度
for(var i=0;i<60;i++){
cxt.save();//保持当前状态
cxt.lineWidth=5;//设置时针的粗细
cxt.strokeStyle="#000";//设置时针颜色
cxt.translate(250,250);//设置0,0点
cxt.rotate(i*6*Math.PI/180);//设置旋转角度(=角度*Math*PI/180)
cxt.beginPath();
cxt.moveTo(0,-180);
cxt.lineTo(0,-190);
cxt.closePath();
cxt.stroke();
cxt.restore();//释放状态
}
//时针
cxt.save();
//设置时针风格
cxt.lineWidth=10;
cxt.strokeStyle="#000";
//设置异次元空间的0,0点
cxt.translate(250,250);
cxt.rotate(hour*30*Math.PI/180)//设置旋转角度
cxt.beginPath();
cxt.moveTo(0,-140);
cxt.lineTo(0,10);
cxt.closePath();
cxt.stroke();
cxt.restore(); //分针
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="#000";
//设置异次元空间的0,0点
cxt.translate(250,250);
cxt.rotate(min*6*Math.PI/180)//设置旋转角度
cxt.beginPath();
cxt.moveTo(0,-160);
cxt.lineTo(0,15);
cxt.closePath();
cxt.stroke();
cxt.restore(); //秒针
cxt.save();
cxt.lineWidth=3;
cxt.strokeStyle="red";
//设置异次元空间的0,0点
cxt.translate(250,250);
cxt.rotate(sec*6*Math.PI/180)//设置旋转角度
cxt.beginPath();
cxt.moveTo(0,-170);
cxt.lineTo(0,20);
cxt.closePath();
cxt.stroke();
//画出时针,分针,秒针的交叉点
cxt.beginPath();
cxt.arc(0,0,5,0,360,false);
//设置填充样式
cxt.fillStyle="yellow";
cxt.fill();
//设置笔触样式
cxt.stroke();
//设置秒针钱小圆点
cxt.beginPath();
cxt.arc(0,-150,5,0,360,false);
//设置填充样式
cxt.fillStyle="yellow";
cxt.fill();
//设置笔触样式
cxt.stroke();
cxt.restore();
}
//使用setInterval(代码,毫秒时间)时钟转动
drawClock();
setInterval(drawClock,1000);
</script>
</body> </html>

显示效果:

html5学习(一)--canvas画时钟