效果图:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body{
background-color: black;
}
#c1{
background-color: white;
}
</style>
</head>
<body>
<canvas id="c1" width="400" height="400"></canvas>
<script>
var oC = document.querySelector("#c1");
var oGc = oC.getContext("2d");
setInterval(showTime,1000);
showTime();
function showTime(){
oGc.clearRect(0,0,oC.offsetWidth,oC.offsetHight);
oGc.save();
//表盘的小刻度
oGc.beginPath();
for(i=0;i<60;i++){
oGc.moveTo(200,200);
oGc.arc(200,200,140,i*6*Math.PI/180,(i+1)*6*Math.PI/180);
}
oGc.stroke();
oGc.beginPath();
oGc.fillStyle = "white";
oGc.arc(200,200,130,0,360*Math.PI/180);
oGc.fill();
//表盘的大刻度
oGc.beginPath();
oGc.lineWidth = "2";
for(i=0;i<12;i++){
oGc.moveTo(200,200);
oGc.arc(200,200,140,i*30*Math.PI/180,(i+1)*30*Math.PI/180);
}
oGc.stroke();
oGc.beginPath();
oGc.fillStyle = "white";
oGc.arc(200,200,125,0,360*Math.PI/180);
oGc.fill();
//获取时间
var nowT = new Date();
var h = nowT.getHours();
var m = nowT.getMinutes();
var s = nowT.getSeconds();
var iH = (h*30+m*0.5-90)*Math.PI/180;
var iM = (m*6+s*0.1-90)*Math.PI/180;
var iS = (s*6-90)*Math.PI/180;
//绘指针
oGc.beginPath();
oGc.lineWidth = "4";
oGc.moveTo(200,200);
oGc.arc(200,200,70,iH,iH,false);
oGc.stroke();
oGc.beginPath();
oGc.lineWidth = "3";
oGc.strokeStyle = "green";
oGc.moveTo(200,200);
oGc.arc(200,200,90,iM,iM);
oGc.stroke();
oGc.beginPath();
oGc.lineWidth = "2";
oGc.strokeStyle = "red";
oGc.moveTo(200,200);
oGc.arc(200,200,120,iS,iS,false);
oGc.stroke();
oGc.restore();
}
</script>
</body>
</html>
h5中canvas相关的知识点:
save() canvas2D API通过将当前状态放入栈中,保存canvas全部状态的方法,调用sava时,将样式容器里的状态压入样式表。
restore() 调用restore时,将样式栈的栈顶状态弹出到样式容器里进行覆盖。
clearRect(x,y,width,height) 清楚指定矩形区域,让清除部分完全透明。
x与y指定了画布上所绘制的矩形的左上角(相对于原点)的坐标。
lineWidth属性 设置当前绘线的粗细。
fillStyle属性 设置图形的填充颜色。
closePath() 此方法会通过绘制一条从当前点到开始点的直线来闭合图形。
stroke() 通过线条来绘制图形轮廓。(不会自动调用closePath())
fill() 通过填充区域的内容区域生成实心的图形。(会自动调用closePath())
arc(x,y,radius,startAngle,endAngle,anticlockwise) 画一个以(x,y)为圆心的以radius为半径的圆弧,从 startAngle开始到endAngle 结束,按照anticlockwise给定的方向(默认为顺时针)生成。
JS中用到的知识点:
setInterval() 定时调用。
参数:1 . 回调函数,该函数会每隔一段时间被调用一次。
2. 每次调用间隔的时间,单位毫秒。
Math.PI()圆周率。
getHours()获取当前对象的小时。
getMinutes()获取当前对象的分钟。
getSeconds()获取当前对象的秒。