css htm5 canvas时钟

完整的代码, 可以复制引用


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
body{ background:black;}
#c1{ background:white;}
</style>

<script>
// 页面加载完成后执行的函数
window.onload = function(){
// 获取canvas元素
var oC = document.getElementById('c1');
// 获取canvas的2D上下文
var oGC = oC.getContext('2d');

// 定义画表盘和指针的函数
function toDraw(){
// 中心点的坐标
var x = 200;
var y = 200;
// 表盘半径
var r = 150;

// 清除画布内容
oGC.clearRect(0,0,oC.width,oC.height);

// 获取当前时间
var oDate = new Date();
var oHours = oDate.getHours();
var oMin = oDate.getMinutes();
var oSen = oDate.getSeconds();

// 计算时、分、秒针的角度
var oHoursValue = (-90 + oHours*30 + oMin/2) * Math.PI/180;
var oMinValue = (-90 + oMin*6) * Math.PI/180;
var oSenValue = (-90 + oSen*6) * Math.PI/180;

// 画出表盘的外围刻度线(总共60条,代表每分钟的刻度)
oGC.beginPath();
for(var i=0;i<60;i++){
oGC.moveTo(x,y);
oGC.arc(x,y,r,6*i*Math.PI/180,6*(i+1)*Math.PI/180,false);
}
oGC.closePath();
oGC.stroke();

// 画出表盘内部的白色区域,覆盖外围刻度线的部分内容
oGC.fillStyle = 'white';
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*19/20,0,360*(i+1)*Math.PI/180,false);
oGC.closePath();
oGC.fill();

// 画出表盘的小时刻度线(总共12条)
oGC.lineWidth = 3;
oGC.beginPath();
for(var i=0;i<12;i++){
oGC.moveTo(x,y);
oGC.arc(x,y,r,30*i*Math.PI/180,30*(i+1)*Math.PI/180,false);
}
oGC.closePath();
oGC.stroke();

// 画出表盘内部的白色区域,覆盖小时刻度线的部分内容
oGC.fillStyle = 'white';
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*18/20,0,360*(i+1)*Math.PI/180,false);
oGC.closePath();
oGC.fill();

// 画出时针
oGC.lineWidth = 5;
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*10/20,oHoursValue,oHoursValue,false);
oGC.closePath();
oGC.stroke();

// 画出分针
oGC.lineWidth = 3;
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*14/20,oMinValue,oMinValue,false);
oGC.closePath();
oGC.stroke();

// 画出秒针
oGC.lineWidth = 1;
oGC.beginPath();
oGC.moveTo(x,y);
oGC.arc(x,y,r*19/20,oSenValue,oSenValue,false);
oGC.closePath();
oGC.stroke();
}

// 每隔1秒重绘一次,实现时钟的动态效果
setInterval(toDraw,1000);

// 页面加载完成后首次绘制时钟
toDraw();
}

</script>
</head>

<body>
<canvas id="c1" width="400" height="400"></canvas>
</body>
</html>

posted on 2021-10-26 23:03  完美前端  阅读(57)  评论(0)    收藏  举报

导航