利用canvas画一个钟表(时分秒联动)
canvas
- 前段时间做微信小程序项目,用到了微信canvas组件生成分享海报,很多东西都生疏了,就想着复习一下canvas的常用知识做一个clock出来。查阅canvas技术文档和相关资料,现将自己整理的代码和自己的理解记录在此,加深记忆,方便以后查阅。也希望有能看到本文的各位朋友批评指正。
- 代码之前 先上效果图吧
- 代码扑面而来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>画布-钟表</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<canvas id='clock' width='600' height='600' style="margin: 150px;"></canvas>
<script>
var canvas = document.getElementById('clock');
const cxt = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
var r = width / 2;
function drawBg() {
cxt.save();
cxt.translate(r,r);
cxt.beginPath();
cxt.arc(0, 0, r-8, 0, 2*Math.PI,true);
cxt.lineWidth = 8;
cxt.stroke();
let hour = [3,4,5,6,7,8,9,10,11,12,1,2];
let hour_rad = 2*Math.PI/12;
cxt.font = "40px sans-serif";
cxt.textAlign = "center";
cxt.textBaseline = "middle";
let r1 = r - 65;
let r2 = r - 23;
for(var i in hour){
cxt.fillStyle = "#000"
cxt.fillText(hour[i],r1*Math.cos(i*hour_rad),r1*Math.sin(i*hour_rad))
}
let minute_rad = 2*Math.PI/60;
for(i = 0; i <= 60; i ++) {
let x = r2*Math.cos(i*minute_rad);
let y = r2*Math.sin(i*minute_rad);
cxt.beginPath();
if(i % 15 == 0){
cxt.fillStyle = "red";
cxt.arc(x ,y , 5, 0, 2*Math.PI, true);
}
else if(i % 5 == 0){
cxt.fillStyle = "#000";
cxt.arc(x ,y , 4, 0, 2*Math.PI, true);
}
else{
cxt.fillStyle = "#bbb";
cxt.arc(x ,y , 3, 0, 2*Math.PI, true);
}
cxt.fill();
}
cxt.beginPath();
cxt.arc(0, 0, r-32, 0, 2*Math.PI,true);
cxt.lineWidth = 3;
cxt.stroke();
}
function drawHour(hour,minute,second) {
cxt.save();
var rad = 2 * Math.PI * ( hour/12 + minute/720 + second/43200);
cxt.beginPath();
cxt.rotate(rad);
cxt.moveTo(0, 10);
cxt.lineTo(0, -r/2);
cxt.lineWidth = 10;
cxt.lineCap = "round";
cxt.stroke();
cxt.restore();
}
function drawMinute(minute,second) {
cxt.save();
var rad = 2 * Math.PI * (minute/60 + second/3600);
cxt.beginPath();
cxt.rotate(rad);
cxt.moveTo(0, 15);
cxt.lineTo(0, -r/1.5);
cxt.lineWidth = 6;
cxt.lineCap = "round";
cxt.stroke();
cxt.restore();
}
function drawSecond(second) {
cxt.save();
var rad = 2 * Math.PI * (second / 60) ;
cxt.beginPath();
cxt.rotate(rad);
cxt.moveTo(0, 25);
cxt.lineTo(2, 25);
cxt.lineTo(-2, 25);
cxt.lineTo(-1, -r/1.25);
cxt.lineTo(1, -r/1.25);
cxt.lineTo(2, 25);
cxt.lineWidth = 2;
cxt.fillStyle = "#f00";
cxt.fill();
cxt.restore();
}
function drawDot() {
cxt.beginPath();
cxt.arc(0, 0, 8, 0, 2*Math.PI,true);
cxt.fillStyle = "red";
cxt.fill();
}
setInterval(function(){
let second = new Date().getSeconds();
let minute = new Date().getMinutes();
let hour = new Date().getHours();
cxt.clearRect(0, 0, width, height);
drawBg();
drawHour(hour,minute,second);
drawMinute(minute,second);
drawSecond(second);
drawDot();
cxt.restore();
},1000)
</script>
</body>
</html>
小结:
- 计算刻度位置坐标时用到了js中Math对象的sin()和cos()方法,它们用到的是弧度rad参数,而不是角度,所以应先理解弧度的概念及圆周的弧度与角度的关系。可参考 百度百科=>弧度