Canvas绘制时钟
话不多说,直接上代码.
//HTML页面部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时钟</title>
<script src="./jquery-3.5.1.min.js"></script>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
//JS部分
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
resizeCanvas();
//移动坐标轴
ctx.translate(400,300);
//时钟圆盘绘制
function drawCirle(){
ctx.beginPath();
ctx.arc(0,0,200,0,Math.PI*2)
ctx.lineWidth = 10;
ctx.strokeStyle = "#dddddd"
ctx.stroke();
ctx.closePath();
}
//分钟刻度绘制
function drawMin(){
for(let i=0;i<60;i++){
ctx.restore()
ctx.save()
ctx.rotate(Math.PI/30*i)
ctx.beginPath();
ctx.moveTo(185,0);
ctx.lineTo(200,0);
ctx.lineWidth = 3;
ctx.strokeStyle = "#d8d8d8"
ctx.stroke();
ctx.closePath()
}
}
//小时刻度绘制
function drawHour(){
for(let i=0;i<12;i++){
ctx.restore()
ctx.save();
ctx.rotate(Math.PI/6*i)
ctx.beginPath();
ctx.moveTo(180,0);
ctx.lineTo(200,0);
ctx.lineWidth = 10;
ctx.strokeStyle = "red"
ctx.stroke();
ctx.closePath()
}
}
//获取当前时间,并进行指针的绘制
drawPointer()
function drawPointer(){
ctx.restore()
//删除画布内容,重绘所有内容
ctx.clearRect(-400,-300,canvas.width,canvas.height)
drawCirle()
drawMin()
drawHour()
let currentDate = new Date();
let curHour = currentDate.getHours();
let curMin = currentDate.getMinutes();
let curSec = currentDate.getSeconds();
drawSecond(curSec)
drawMinPointer(curMin,curSec)
drawHourPointer(curHour,curMin)
}
//绘制秒钟指针
function drawSecond(curSec){
ctx.restore();
ctx.save()
ctx.rotate(-Math.PI/2);
//ctx.save();
ctx.rotate(Math.PI/30*curSec)
ctx.beginPath();
ctx.moveTo(-20,0);
ctx.lineTo(170,0);
ctx.lineWidth = 2;
ctx.strokeStyle = "#3498db"
ctx.stroke()
ctx.closePath();
}
//绘制分钟指针
function drawMinPointer(curMin,curSec){
ctx.restore();
ctx.save();
ctx.rotate(-Math.PI/2)
ctx.rotate(Math.PI/30*curMin+curSec/60*Math.PI/30)
ctx.beginPath();
ctx.moveTo(-20,0);
ctx.lineTo(160,0);
ctx.lineWidth = 3;
ctx.strokeStyle = "#f39c12";
ctx.stroke()
ctx.closePath();
}
//绘制时钟指针
function drawHourPointer(curHour,curMin){
ctx.restore();
ctx.save();
ctx.rotate(-Math.PI/2);
ctx.rotate(Math.PI/6*curHour+curMin/60*Math.PI/6)
ctx.beginPath();
ctx.moveTo(-20,0);
ctx.lineTo(150,0);
ctx.lineWidth = 4;
ctx.strokeStyle = "#7f8c8d";
ctx.stroke();
ctx.closePath();
}
//定时器,进行时钟的绘制
setInterval(drawPointer,1000)
//以下代码为画布大小随窗口大小改变而改变,可要可不要
$(window).resize(resizeCanvas);
function resizeCanvas() {
$(canvas).attr("width", $(window).get(0).innerWidth);
$(canvas).attr("height", $(window).get(0).innerHeight);
};