用canvas画时钟

效果图在博客首页上。

html:

 <canvas id="canvas" >Your browser does not support canvas</canvas>

css:

canvas {
display:block;
margin:60px auto;

border:1px solid black;

}

js:

<script>
window.onload=function(){
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext("2d");
canvas.width=800;
canvas.height=600;

/*获取时间*/
function colock(){
var myDate=new Date();
var myHour=myDate.getHours();
var myMin=myDate.getMinutes();
var mySec=myDate.getSeconds();

/*背景*/
ctx.save();
ctx.rect(0,0,800,600);
ctx.fillStyle='#ddd';
ctx.fill();
ctx.stroke();
ctx.restore();

/*表盘*/
ctx.save();
ctx.beginPath();
ctx.arc(400,300,200,0,2*Math.PI,true);
ctx.fillStyle='#fff';
ctx.strokeStyle="#ffee00";
ctx.lineWidth=20;
ctx.fill();
ctx.closePath();
ctx.stroke();
ctx.restore();


/*数字*/
ctx.save();
ctx.beginPath();
ctx.font="15px Arial";
ctx.fillStyle='black';
var num=['3','4','5','6','7','8','9','10','11','12','1','2'];
var r=150;
//ctx.arc(100,100,150,0,2*Math.PI,true);
for(var i=0;i<12;i++){
ctx.fillText(num[i],400+r*Math.cos(i*30*Math.PI/180),300+r*Math.sin(i*30*Math.PI/180));
}
ctx.closePath();
ctx.restore();

/*时针*/
ctx.save();
ctx.beginPath();
ctx.translate(400,300);
ctx.rotate((myHour-3)*30*Math.PI/180+(30*myMin/60)*Math.PI/180);
ctx.lineTo(-20,0);
ctx.lineTo(60,0);
ctx.lineWidth=8;
ctx.closePath();
ctx.strokeStyle='black';
ctx.stroke();
ctx.restore();

/*分针*/
ctx.save();
ctx.beginPath();
ctx.translate(400,300);
ctx.rotate((myMin-15)*6*Math.PI/180+Math.PI/2+(6*mySec/60)*Math.PI/180);
ctx.lineTo(0,20);
ctx.lineTo(0,-90);
ctx.lineWidth=6;
ctx.closePath();
ctx.strokeStyle='#333';
ctx.stroke();
ctx.restore();

/*秒针*/
ctx.save();
ctx.beginPath();
ctx.translate(400,300);
ctx.rotate((mySec-15)*6*Math.PI/180+Math.PI/2);
ctx.lineTo(0,20);
ctx.lineTo(0,-120);
ctx.lineWidth=3;
ctx.closePath();
ctx.strokeStyle='red';
ctx.stroke();
ctx.restore();
}

colock();
setInterval(colock,1000);

}

原文地址:https://www.cnblogs.com/lionisnotkitty/p/5999316.html