您的位置:首页 > Web前端 > HTML5

html5 实例[1] 小时钟

2014-04-21 15:31 113 查看


<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>

<canvas id="clock" width="500" height="500">
浏览器老古董升级吧
</canvas>

<script>

var clock = document.getElementById('clock');
var cxt = clock.getContext('2d');

function i(){

// 清除画布
cxt.clearRect(0,0,500,500);

var now = new Date();
var sec = now.getSeconds();
var min = now.getMinutes();
var hour = now.getHours();
// 小时必须获取浮点类型(小时+分数/60)
hour = hour+min/60;
// 小时格式
hour = hour>12 ? hour-12 : hour;

// 表盘(蓝色)
cxt.lineWidth="10"; // 边宽
cxt.strokeStyle="#abcdef"; // 蓝色
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="7";
cxt.strokeStyle="#000";
cxt.translate(250,250); // 先设置00点
cxt.rotate( i*30*Math.PI/180 ); // 角度*Math.PI/180 = 弧度

cxt.beginPath();
cxt.moveTo(0,-170);
cxt.lineTo(0,-190);
cxt.stroke();
cxt.closePath();

cxt.restore();
}
// 分刻度
for(var i=0;i<60;i++){
cxt.save();  // 拿到异次元

cxt.lineWidth="3";
cxt.strokeStyle="orange";
cxt.translate(250,250);
cxt.rotate( i*6*Math.PI/180);

cxt.beginPath(); // 开路径
cxt.moveTo(0,-180); // 围着原点
cxt.lineTo(0,-190); // 到哪
cxt.stroke();// 开画
cxt.closePath(); // 闭路径

cxt.restore();  // 保存当前和异次元相结合的结果
}
// 时针
cxt.save();

cxt.lineWidth="7";
cxt.strokeStyle="#000";

cxt.translate(250,250);
cxt.rotate(hour*30*Math.PI/180);

cxt.beginPath();
cxt.moveTo(0,-150);
cxt.lineTo(0,10);
cxt.stroke();
cxt.closePath();

cxt.restore();
// 分针
cxt.save();

cxt.lineWidth="5";
cxt.strokeStyle="#000";

cxt.translate(250,250);
cxt.rotate(min*6*Math.PI/180);

cxt.beginPath();
cxt.moveTo(0,-150);
cxt.lineTo(0,10);
cxt.stroke();
cxt.closePath();

cxt.restore();
// 秒针
cxt.save();

cxt.lineWidth="2";
cxt.strokeStyle="red";

cxt.translate(250,250);
cxt.rotate(sec*6*Math.PI/180);

cxt.beginPath();
cxt.moveTo(0,-160);
cxt.lineTo(0,30);
cxt.stroke();
cxt.closePath();

// 画出时分秒的交叉点
cxt.beginPath();
cxt.arc(0,0,5,0,360,false);
cxt.fillStyle="gray";
cxt.fill();
cxt.strokeStyle="red";
cxt.stroke();
cxt.closePath()

cxt.beginPath();
cxt.arc(0,-150,5,0,360,false);
cxt.fillStyle="gray";
cxt.fill();
cxt.strokeStyle="red";
cxt.stroke();
cxt.closePath();

cxt.restore();
}

// 使用 setInterval(代码,时间毫秒) 让时钟动起来
i();
setInterval(i,500);
</script>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: