Js用Canvas实现简单时钟

才开始学习canvas,利用canvas的实现了简单的时钟。效果图如下:

这里写图片描述

思路如下:
利用setInterval()注册每隔1秒触发的画钟事件。drawClock()流程图如下:

Created with Raphaël 2.1.0 start caculate hand angle clear Canvas draw panel draw text draw hands end

源代码如下:

<!DOCTYPE html>
<html>
<head>
<title>clock</title>
<style type="text/css">
    canvas {
        position: absolute;
        margin: -100px;
        top: 50%;
        left: 50%;
    }
</style>
</head>
<body>
<canvas id="clock" width="200px" height="200px">This is a clock</canvas>
<script type="text/javascript">
//clock
var drawing = document.querySelector('#clock');
var context = drawing.getContext('2d');
var drawClock = function () {
    var time = new Date();
    var second = time.getSeconds();
    var minute = time.getMinutes();
    var hour = time.getHours();
    var secondhandAngle = second * Math.PI / 30;
    var minutehandAngle = minute * Math.PI / 30;
    var hourhandAngle = hour * Math.PI / 12;
    //clear canvas
    context.clearRect(0, 0, 200, 200);
    //begin draw
    context.beginPath();

    //draw panel
    context.arc(100, 100, 100, 99, 0, 2 * Math.PI, false);
    context.moveTo(194, 100);
    context.arc(100, 100, 94, 0, 2 * Math.PI, false);

    //draw text
    context.font = "bold 14px Consolar";
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.fillText('12', 100, 20);
    context.fillText('3', 180, 100);
    context.fillText('6', 100, 180);
    context.fillText('9', 20, 100);

    //draw second hand
    context.moveTo(100, 100);
    context.lineTo(100 + 80 * Math.sin(secondhandAngle), 100 - 80 * Math.cos(secondhandAngle));
    //draw minute hand
    context.moveTo(100, 100);
    context.lineTo(100 + 65 * Math.sin(minutehandAngle), 100 - 65 * Math.cos(minutehandAngle));
    //draw hour hand
    context.moveTo(100, 100);
    context.lineTo(100 + 50 * Math.sin(hourhandAngle), 100 - 50 * Math.cos(hourhandAngle));
    //complete draw
    context.stroke();
};
setInterval(drawClock, 1000);
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值