canvas基础—02demo之(钟表)
1.钟表
demo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas学习</title>
<style>
body{background: black}
#c1{background: white}
span{color: white}
</style>
<script type="text/javascript">
window.onload = function(){
var oC = document.getElementById('c1');
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 //分针为30分,时针就走15度
var oMinValue = (-90+oMin*6)*Math.PI/180
var oSenValue = (-90+oSen*6)*Math.PI/180
// 绘制秒刻度
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*Math.PI/180,false)
oGC.closePath()
oGC.fill()
// 绘制分刻度
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*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()
}
setInterval(toDraw,1000)
toDraw()
}
</script>
</head>
<body>
<canvas id="c1" width="400" height="400">
<span>不支持canvas浏览器</span>
</canvas>
</body>
</html>
题外话
关于这块setInterval(toDraw,1000) ,为什么不是setInterval(toDraw(),1000)。这篇文章给出了答案
https://segmentfault.com/q/1010000005712894/a-1020000005713368