您的位置:首页 > Web前端 > JavaScript

Js用Canvas实现简单时钟

2017-08-11 15:23 726 查看
才开始学习canvas,利用canvas的实现了简单的时钟。效果图如下:



思路如下:

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

Created with Raphaël 2.1.0startcaculate 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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  canvas javascript