<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
text-align: center;
margin-top: 20px;
}
#canvas{
border: 1px solid #000;
}
</style>
<body>
<div>
<canvas id="canvas" width="400" height="400"></canvas>
</div>
<script type="text/javascript">
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var width=ctx.canvas.width;
var height=ctx.canvas.height;
var r=width/2;
function drawbackgroud(){
ctx.translate(r,r);
ctx.beginPath();
ctx.lineWidth=10;
ctx.fillStyle="#000";
ctx.arc(0,0,r-5,0,Math.PI*2,false);
ctx.stroke();
var hourtime=[3,4,5,6,7,8,9,10,11,12,1,2];
for (var i = 0; i <12; i++) {
var timetex=hourtime[i];
var rad=Math.PI*2/12*i;
var x=Math.cos(rad)*(r-30);
var y=Math.sin(rad)*(r-30);
ctx.fillText(timetex,x,y);
ctx.textAlign="center";
ctx.textBaseline="middle";
}
for (var i = 0; i <60; i++) {
var rad=Math.PI*2/60*i;
var x=Math.cos(rad)*(r-18);
var y=Math.sin(rad)*(r-18);
ctx.beginPath();
if(i%5==0){
ctx.arc(x,y,2,0,Math.PI*2,false);
ctx.fillStyle="#000";
}else{
ctx.arc(x,y,2,0,Math.PI*2,false);
}
ctx.fill();
ctx.fillStyle="#ccc";
}
}
function drawhour(hour,minute){
ctx.save();
ctx.beginPath();
ctx.lineWidth=6;
ctx.lineCap="round";
var rad=Math.PI*2/12*hour;
var mad=Math.PI*2/12/60*minute;
ctx.rotate(rad+mad);
ctx.moveTo(0,10);
ctx.lineTo(0,-r/2);
ctx.stroke();
ctx.restore();
}
function drawminute(minute){
ctx.save();
ctx.beginPath();
ctx.lineWidth=3;
ctx.lineCap="round";
var rad=Math.PI*2/60*minute;
ctx.rotate(rad);
ctx.moveTo(0,15);
ctx.lineTo(0,-r+30);
ctx.strokeStyle="#ccc";
ctx.stroke();
ctx.restore();
}
function drawsecond(second){
ctx.save();
ctx.restore();
ctx.beginPath();
ctx.lineWidth=3;
ctx.lineCap="round";
ctx.fillStyle="red";
var rad=Math.PI*2/60*second;
ctx.rotate(rad);
ctx.moveTo(-2,20);
ctx.lineTo(2,20);
ctx.lineTo(1,-r+18);
ctx.lineTo(-1,-r+18);
ctx.fill();
ctx.restore();
}
function drawdow(){
ctx.beginPath();
ctx.arc(0,0,5,0,Math.PI*2,false);
ctx.fillStyle="#fff";
ctx.fill();
ctx.restore();
}
drawbackgroud();
function draw(){
var data=new Date();
var hour=data.getHours();
var minute=data.getMinutes();
var second=data.getSeconds();
drawhour(hour,minute);
drawminute(minute);
drawsecond(second);
ctx.restore();
}
drawdow();
setInterval(draw,1000)
</script>
</body>
</html>
在drawBackground()方法开始就要保存画布,ctx.save(),并且drawBackground()方法是在draw()方法里调用,而不是在外部调用。在draw()方法开始的时候就要“在给定的矩形内清除指定的像素”ctx.clearRect(0, 0, width, height);
建议可以再次跟着视频做一次,老师其实讲得很详细了~加油
仅供参考