用canvas和js画了个钟表,跟大家分享一下

<pre name="code" class="javascript">(function () {
var mycanvas=document.getElementById("mycanvas");
var otex=mycanvas.getContext("2d");
function time() {
    otex.clearRect(0,0,500,500);
    //画大圆
    otex.beginPath();
    otex.arc(250,250,200,0,2*Math.PI);
    otex.strokeStyle="#abcdef";
    otex.lineWidth=10;
    otex.closePath();
    otex.stroke();

    //秒针
    otex.strokeStyle="grey";
    otex.lineWidth=5;
    for(var i=0;i<60;i++){
        otex.save();
        otex.beginPath();
        otex.translate(250,250);
        otex.rotate(i*6*Math.PI/180);
        otex.moveTo(0,-195);
        otex.lineTo(0,-180);
        otex.closePath();
        otex.stroke();
        otex.restore();
    }


    //画时针针
    otex.strokeStyle="blue";
    otex.lineWidth=10;

    for(var i=0;i<12;i++){
        otex.save();//记得使用
        otex.beginPath();
        otex.translate(250,250);
        otex.rotate(i*30*Math.PI/180);
        otex.moveTo(0,-175);
        otex.lineTo(0,-195);
        otex.closePath();
        otex.stroke();
        otex.restore();//记得使用
    }

    var now=new Date();
    var h=now.getHours();
    var m=now.getMinutes();
    var s=now.getSeconds();

    //计算小时
    otex.save();//记得使用
    otex.beginPath();
    otex.strokeStyle="blue";
    otex.lineWidth=5;
    otex.translate(250,250);
    otex.rotate((h+m/60)*30*Math.PI/180);
    otex.moveTo(0,10);
    otex.lineTo(0,-125);
    otex.closePath();
    otex.stroke();
    otex.restore();//记得使用

    //分
    otex.save();//记得使用
    otex.beginPath();
    otex.strokeStyle="red";
    otex.lineWidth=4;
    otex.translate(250,250);
    otex.rotate((m+s/60)*6*Math.PI/180);
    otex.moveTo(0,10);
    otex.lineTo(0,-165);
    otex.closePath();
    otex.stroke();
    otex.restore();//记得使用

    //秒
    otex.save();//记得使用
    otex.beginPath();
    otex.strokeStyle="red";
    otex.lineWidth=4;
    otex.translate(250,250);
    otex.rotate(s*6*Math.PI/180);
    otex.moveTo(0,10);
    otex.lineTo(0,-185);
    otex.closePath();
    otex.stroke();
    otex.restore();//记得使用
}
    time();
    setInterval(time,1000)
})();

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>钟表</title></head><style> *{margin: 0;padding: 0;}</style><body> <canvas id="mycanvas" width="500" height="600" style=" position: relative;left:0;right:0;margin:0 auto"> </canvas><script src="main.js"></script></body>
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值