理论基础:
掌握canvas绘制圆形,以及绘制扇形的弧度计算(涉及三角函数),掌握canvas的动画基础和绘制图片》了解更多
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas width="500" height="500" style="border: 1px solid #ccc"></canvas>
<script>
var ctx = document.querySelector("canvas").getContext("2d");
var checkNum = function (num) {
return num >= 10 ? num : "0" + num;
}
function clock() {
//绘制背景图
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0, 255, 255, 10, 10, 480, 480);
//当图片加载完后执行
//获取时分秒
var dt = new Date();
var h = dt.getHours();
var m = dt.getMinutes();
var s = dt.getSeconds();
var timeTxt = checkNum(h) + ":" + checkNum(m) + ":" + checkNum(s);
//绘制文字
ctx.beginPath();
ctx.font = "20px 微软雅黑";
ctx.textAlign = "center";
ctx.fillStyle = "orange";
ctx.fillText(timeTxt, 250, 410);
//精确时分
h = h > 12 ? (h - 12) : h;
h += m / 60;
m += s / 60;
ctx.beginPath();
ctx.arc(250, 250, 200, 0, Math.PI * 2);
ctx.strokeStyle = "orange";
ctx.lineWidth = 5;
// ctx.fillStyle = "rgb(60,253,126)";
// ctx.fill();
ctx.stroke();
ctx.clip();//裁剪
//绘制圆心
ctx.beginPath();
ctx.arc(250, 250, 8, 0, Math.PI * 2);
ctx.fillStyle = "orange";
ctx.fill();
//时刻度
for (var i = 0; i < 12; i++) {
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(i * 30 * Math.PI / 180);
ctx.moveTo(0, -180);
ctx.lineTo(0, -200);
ctx.lineCap = "round";
ctx.strokeWidth = 7;
ctx.strokeStyle = "orange";
ctx.stroke();
ctx.restore();//恢复当前状态
}
//分刻度
for (var i = 0; i < 60; i++) {
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(i * 6 * Math.PI / 180);
ctx.moveTo(0, -190);
ctx.lineTo(0, -200);
ctx.lineCap = "round";
ctx.strokeWidth = 7;
ctx.strokeStyle = "orange";
ctx.stroke();
ctx.restore();//恢复当前状态
}
//时针
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(h * 30 * Math.PI / 180);
ctx.moveTo(0, 0);
ctx.lineTo(0, -100);
ctx.lineCap = "round";
ctx.strokeWidth = 7;
ctx.strokeStyle = "orange";
ctx.stroke();
ctx.restore();//恢复当前状态
//分针
// 保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(m * 6 * Math.PI / 180);
ctx.moveTo(0, 0);
ctx.lineTo(0, -140);
ctx.lineCap = "round";
ctx.strokeWidth = 4;
ctx.strokeStyle = "orange";
ctx.stroke();
ctx.restore();//恢复当前状态
//秒针
//保存当前的状态
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(s * 6 * Math.PI / 180);
//秒针上的圆
ctx.arc(0, -120, 5, 0, Math.PI * 2);
ctx.fillStyle = "green";
ctx.fill();
ctx.moveTo(0, 0);
ctx.lineTo(0, -160);
ctx.lineCap = "round";
ctx.strokeWidth = 2;
ctx.strokeStyle = "orange";
ctx.stroke();
ctx.restore();//恢复当前状态
}
img.src = "1.jpg";
}
setInterval(clock, 1000);
clock();
</script>
</body>
</html>
最终效果图