canvas标签结合javascript做出动态时钟效果

代码如下:

<!doctype html>
<head>
<meta charset="utf-8">
<style type="text/css">
body{
background: purple;
}
</style>
</head>
<body>
<canvas id="liuzhe" width="500" height="500"></canvas>
<script type="text/javascript">
var clock=document.getElementById("liuzhe");
var cxt=clock.getContext("2d");
    function drawclock(){
    //清除画布
    cxt.clearRect(0,0,500,500)
var now=new Date();
var sec=now.getSeconds();
var min=now.getMinutes();
var hour=now.getHours();
hour=hour>12?hour-12:hour;




//画圆
cxt.lineWidth=10;
cxt.strokeStyle="red";
cxt.beginPath();
cxt.arc(250, 250, 200, 0, 360, false);
cxt.closePath();
cxt.stroke();


//小时
for(var i=0;i<12;i++){
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="#000";
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.lineWidth=5;
cxt.strokeStyle="#000"
cxt.translate(250, 250);
cxt.rotate(sec*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="#000";
    cxt.translate(250, 250);
    cxt.rotate(hour*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, -140);
cxt.lineTo(0, 10);
cxt.closePath();
cxt.stroke();
    cxt.restore();


//分针
    cxt.save();
    cxt.lineWidth=5;
    cxt.strokeStyle="#000";
    cxt.translate(250, 250);
    cxt.rotate(min*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, -160);
cxt.lineTo(0, 15);
cxt.closePath();
cxt.stroke();
    cxt.restore();


    //秒针
    cxt.save();
    cxt.lineWidth=3;
    cxt.strokeStyle="red";
    cxt.translate(250, 250);
    cxt.rotate(sec*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0, -170);
cxt.lineTo(0, 20);
cxt.closePath();
cxt.stroke();
    cxt.restore();    
}






    //周期循环时间
    setInterval(drawclock, 1000);
</script>
</body>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值