用canvas画一个时钟
h5部分:
<canvas id="canvas" width="400" height="400"> 您的浏览器不支持canvas,请升级浏览器。 </canvas>
javascript部分:
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.style.border = "1px solid #ccc";
function drawClock(){
ctx.clearRect(0,0,400,400);
ctx.strokeStyle = "#dea286";
ctx.lineWidth = "10";
ctx.beginPath();
ctx.arc(200,200,150,0*Math.PI/180,360*Math.PI/180,false);
ctx.stroke();
//时刻度
for(var i = 0; i < 12; i++){
ctx.save();
ctx.lineWidth = "7";
ctx.strokeStyle = "#dea286";
ctx.translate(200,200);
ctx.rotate(i*30*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0, -125);
ctx.lineTo(0, -140);
ctx.closePath();
ctx.stroke();
ctx.closePath();
ctx.restore();
}
//数字
for (var i=0;i<12;i++) {
ctx.beginPath();
var txt = i<1 ? 12 : i;
ctx.font = "12px";
ctx.lineWidth = "2";
ctx.strokeStyle = "#a5735c";
var x = 195+Math.sin(i*30*Math.PI/180)*115;
var y = 205-Math.cos(i*30*Math.PI/180)*115;
ctx.strokeText(txt,x,y);
}
//分刻度
for(var i = 0; i < 60; i++){
ctx.save();
ctx.lineWidth = "4";
ctx.strokeStyle = "#dea286";
ctx.translate(200,200);
ctx.rotate(i*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0, -135);
ctx.lineTo(0, -140);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
//获取时间
var date1 = new Date();
var s = date1.getSeconds();
var m = date1.getMinutes();
var h = date1.getHours();
//时针
ctx.save();
ctx.lineWidth = "7";
ctx.strokeStyle = "#a5735c";
ctx.translate(200,200);
ctx.rotate(h*30*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,-60);
ctx.lineTo(0,8);
ctx.closePath();
ctx.stroke();
ctx.restore();
//分针
ctx.save();
ctx.lineWidth = "5";
ctx.strokeStyle = "#dea286";
ctx.translate(200,200);
ctx.rotate(m*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,-80);
ctx.lineTo(0,10);
ctx.closePath();
ctx.stroke();
ctx.restore();
//秒针
ctx.save();
ctx.lineWidth = "3";
ctx.strokeStyle = "#e9c6c0";
ctx.translate(200,200);
ctx.rotate(s*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(0,-120);
ctx.lineTo(0,12);
ctx.closePath();
ctx.stroke();
//指针中心的小圆点
ctx.beginPath();
ctx.arc(0,0,4,0*Math.PI/180,360*Math.PI/180,false);
ctx.closePath();
ctx.fillStyle = "#aaaaaa";
ctx.fill();
ctx.stroke();
ctx.restore();
}
drawClock();
setInterval(drawClock,1000);
</script>
效果图:

浙公网安备 33010602011771号