The clock effect is seen a lot.
Today, use Canvas to make a clock effect.
HTML is very simple, just a Canvas tag.
<canvas id="can" width="800" height="500"></canvas>
The focus is on JavaScript.
let can = document.querySelector("#can");
let ctx = can.getContext("2d");
let myset = setInterval(function(){
aniMain(); // 主函数
},1000);
function aniMain(){
// 获取系统时间
let mytime = new Date();
let sz = mytime.getHours();
let fz = mytime.getMinutes();
let mz = mytime.getSeconds();
// 整个清空画布
ctx.clearRect(0,0,can.width,can.height);
// 绘图
drawClock();
drawKedu();
fenZhen( fz );
shiZhen( sz ,fz);
miaoZhen( mz );
wenben(sz,fz,mz);
}
function drawClock(){
ctx.save();
ctx.translate( can.width/2 ,can.height/2);
ctx.lineWidth = 10;
ctx.strokeStyle = "#300";
ctx.beginPath();
ctx.arc(0,0,200,0,2*Math.PI);
ctx.stroke();
ctx.restore();
}
function drawKedu(){
ctx.save();
ctx.translate( can.width/2 ,can.height/2);
for( var i=0 ; i <= 59 ; i++){
ctx.rotate(6 * Math.PI / 180 );
ctx.beginPath();
ctx.moveTo( 180, 0 );
ctx.lineTo( 190,0);
ctx.stroke();
}
ctx.restore();
// 大刻度
ctx.save();
ctx.translate( can.width/2 ,can.height/2);
ctx.lineWidth = 5 ;
for(i=0; i<=11 ; i++){
ctx.rotate(30 * Math.PI / 180 );
ctx.beginPath();
ctx.moveTo( 170, 0 );
ctx.lineTo( 190,0);
ctx.stroke();
}
ctx.restore();
}
// 秒针
function miaoZhen(mz){
ctx.save();
ctx.translate(can.width/2 , can.height/2);
ctx.strokeStyle = "#f00";
ctx.fillStyle = "#f00";
ctx.rotate( mz*6 *Math.PI / 180 - Math.PI/2);
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(160,0);
ctx.stroke();
ctx.arc(0,0,10,0,2*Math.PI);
ctx.fill();
ctx.restore();
}
// 分针
function fenZhen(fz){
ctx.save();
ctx.translate(can.width/2 , can.height/2);
ctx.strokeStyle = "#000";
ctx.fillStyle = "#000";
ctx.lineWidth = 5;
ctx.rotate( fz*6 *Math.PI / 180 - Math.PI/2);
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(140,0);
ctx.stroke();
ctx.arc(0,0,10,0,2*Math.PI);
ctx.fill();
ctx.restore();
}
// 时针
function shiZhen(sz , fz){
ctx.save();
ctx.translate(can.width/2 , can.height/2);
ctx.strokeStyle = "#000";
ctx.fillStyle = "#000";
ctx.lineWidth = 10;
ctx.rotate( sz*6 *Math.PI / 180 - Math.PI/2 + fz/2*Math.PI/180);
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(110,0);
ctx.stroke();
ctx.arc(0,0,10,0,2*Math.PI);
ctx.fill();
ctx.restore();
}
// 文本
function wenben( sz,fz,mz){
( sz <10 )&&( sz = "0"+sz);
( fz <10 )&&( fz = "0"+fz);
( mz <10 )&&( mz = "0"+mz);
let str = sz + ":" + fz + ":" + mz ;
ctx.save();
ctx.translate( can.width/ 2 , can.height/2);
ctx.font = "30px Arial";
ctx.textAlign = "center" ;
ctx.textBaseline = "top" ;
ctx.fillText( str , 0 , -100);
ctx.restore();
}
The key part of the code is used to store and restore Canvas image coordinate information.
ctx.save(); // 坐标信息存储。
// ... 一番操作,坐标位移,旋转...
ctx.restore(); // 坐标信息复原。