JSFiddle - React, Tailwind, and code Playground
by liyilongcarlos
HTML
<canvas id="canvas" width="500" height="500">请更新浏览器版本</canvas>
JavaScript
var can=document.getElementById("canvas");
var cxt=can.getContext("2d");
function drawClock(){
//清楚画布
cxt.clearRect(0, 0, 500, 500);
//得到当前时间
var time=new Date();
var hours=time.getHours();
var mins=time.getMinutes();
var secs=time.getSeconds();
//转换为12进制
hours=hours>12?hours-12:hours;
//小时必须获得浮点型,不能只显示整点
hours=hours+mins/60;
//先画出表盘
cxt.lineWidth=10;
cxt.strokeStyle="blue";
cxt.beginPath();
cxt.arc(250, 250, 200, 0, 360, false);
cxt.closePath();
cxt.stroke();
//画出时刻
for(var i=0;i<12;i++){
cxt.save();
cxt.beginPath();
cxt.lineWidth=7;
cxt.strokeStyle="black";
//按照圆心来旋转,好计算
cxt.translate(250, 250);
cxt.rotate(i*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, -170);
cxt.lineTo(0, -190);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
for(var i=0;i<60;i++){
cxt.save();
cxt.beginPath();
cxt.lineWidth=5;
cxt.strokeStyle="black";
//按照圆心来旋转,好计算
cxt.translate(250, 250);
cxt.rotate(i*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, -180);
cxt.lineTo(0, -190);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//画出时针
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="black";
cxt.translate(250, 250);
cxt.rotate(hours*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, 15);
cxt.lineTo(0, -130);
cxt.closePath();
cxt.stroke();
cxt.restore();
//分针
cxt.save();
cxt.lineWidth=5;
cxt.strokeStyle="black";
cxt.translate(250, 250);
cxt.rotate(mins*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, 15);
cxt.lineTo(0, -150);
cxt.closePath();
cxt.stroke();
cxt.restore();
//秒针
cxt.save();
cxt.lineWidth=3;
cxt.strokeStyle="red";
cxt.translate(250, 250);
cxt.rotate(secs*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, 15);
cxt.lineTo(0, -172);
cxt.closePath();
cxt.stroke();
//美化 画出中间的小圆点
cxt.beginPath();
cxt.arc(0, 0, 6,...