# 震惊！Canvas原来还能这么搞！代码画一个时钟出来

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>canvas动态时钟</title>
<style>
canvas{
margin: 25px;
}
</style>
<body>
<canvas id="mycanvas" width="520px" height="520px"></canvas>
<script>
var cxt=document.getElementById('mycanvas').getContext('2d')
function drawClock(){
cxt.clearRect(0,0,520,520)
//画表盘
cxt.save()
cxt.translate(260,260)
cxt.beginPath()
cxt.strokeStyle="#4C5A63"
cxt.arc(0,0,250,0,2*Math.PI,false)
cxt.stroke()
cxt.closePath()
cxt.beginPath()
cxt.strokeStyle="black"
cxt.arc(0,0,230,0,2*Math.PI,false)
cxt.stroke()
cxt.restore()
cxt.closePath()

//画时刻度
for (var i=0;i<12;i++){
cxt.beginPath()
cxt.save()
cxt.translate(260,260)
cxt.lineWidth=4
cxt.strokeStyle="#000"
cxt.rotate(i*30*Math.PI/180)
cxt.moveTo(0,-230)
cxt.lineTo(0,-208)
cxt.stroke()
cxt.restore()
cxt.closePath()
}

//画分刻度
for (var i = 0; i < 60; i++) {
cxt.beginPath()
cxt.save()
cxt.translate(260, 260)
cxt.lineWidth = 2
cxt.strokeStyle = 'black'
cxt.rotate(i * 6 * Math.PI / 180)
cxt.moveTo(0, -230)
cxt.lineTo(0, -220)
cxt.stroke()
cxt.restore()
cxt.closePath()
}

//写时间
cxt.beginPath()
cxt.save()
cxt.translate(260,260)
var hourNumbers = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];
hourNumbers.map(function (number, i) {
var x = Math.cos(rad) * (230 - 50);
var y = Math.sin(rad) * (230 - 50);
cxt.textAlign = 'center';
cxt.textBaseline = 'middle';
cxt.fillStyle="#000"
cxt.font = "42px bold Arial";
cxt.fillText(number, x, y)
});
cxt.restore()
cxt.closePath()

//写文字
var now=new Date()//获取目前时间
sec=now.getSeconds()
min=now.getMinutes()
hour=now.getHours()
var endtime=new Date("2020/12/12 00:00:00")
var second=parseInt((endtime.getTime()-now.getTime())/1000)//解析字符串，获取相差秒数
var day=parseInt(second/3600/24)//获取天数
cxt.fillStyle="red"
cxt.font="20px bold 楷体"
cxt.fillText("距2021年考研还剩: "+day+"天",150,350)

//画时针
cxt.save()
cxt.translate(260,260)
cxt.beginPath()
cxt.lineWidth=7
cxt.strokeStyle="black"
cxt.rotate(hour*30*Math.PI/180)
cxt.moveTo(0,20)
cxt.lineTo(0,-140)
cxt.stroke()
cxt.closePath()
//画分针
cxt.beginPath()
cxt.lineWidth=3
cxt.strokeStyle="black"
cxt.rotate(min*6*Math.PI/180)
cxt.moveTo(0,30)
cxt.lineTo(0,-150)
cxt.stroke()
cxt.closePath()
//画秒针
cxt.beginPath()
cxt.lineWidth=2
cxt.strokeStyle="black"
cxt.rotate(sec*6*Math.PI/180)
cxt.moveTo(0,30)
cxt.lineTo(0,-170)
cxt.stroke()
cxt.closePath()
cxt.restore()

//在原点画按钮
cxt.beginPath()
cxt.fillStyle="red"
cxt.strokeStyle="#F5FEDA"
cxt.arc(260,260,7,0,2*Math.PI,false)
cxt.fill()
cxt.stroke()
cxt.closePath()
}
setInterval(drawClock,1000)
</script>
</body>
</html>


02-06 386

09-18

05-28 193

07-15 5091

03-06 614

09-28

07-17 4259

#### 使用Canvas(画布）完成一个时钟

©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。