首页 > 其他 > 详细

h5+canvas绘制动画时钟

时间:2016-08-14 14:21:49      阅读:305      评论:0      收藏:0      [点我收藏+]

h5+canvas绘制动画时钟

效果图,这个是截图,可以动的,

技术分享

代码如下:

<!DOCTYPE html>
<html>
<head>
<title>动画效果</title>
</head>

<body>
<canvas id="anm" width="600" height="600" style="border:1px solid gray"></canvas>
<script type="text/javascript">
//绘制时钟
function drawClock() {
var now = new Date();
var hour = now.getHours(), m = now.getMinutes(), s = now
.getSeconds();
hour = hour >= 12 ? hour - 12 : hour;
var c = document.getElementById("anm");
var ctx = c.getContext("2d");
//初始化save() 方法
ctx.save();
//首先清除画布,否则会重叠绘制
ctx.clearRect(0, 0, 400, 400);
//重新映射画布上的(0,0)位置
ctx.translate(140, 140);
//选择画布角度 因为默认的角度0° 是向右,而我们要的0点时候要在上方,逆时针旋转90度得到
ctx.rotate(-Math.PI / 2);
//设置路径颜色
ctx.strokeStyle = "red";
//设置线的宽度
ctx.lineWidth = 2;
//向线条的每个末端添加正方形线帽
ctx.lineCap = "square";
//保存当前状态
ctx.save();
//绘制小时刻度
ctx.beginPath();
for (var i = 0; i < 12; i++) {
ctx.rotate(30 * Math.PI / 180);
ctx.moveTo(110, 0);
ctx.lineTo(120, 0);
}
ctx.stroke();
//取出保存的画布状态进行融合
ctx.restore();
//保存当前的画布状态
ctx.save();
//画分钟刻度
ctx.beginPath();
for (var i = 0; i < 60; i++) {
ctx.rotate(6 * Math.PI / 180);
ctx.moveTo(117, 0);
ctx.lineTo(120, 0);
}
ctx.stroke();
ctx.restore();
ctx.save();
//画时针
ctx.beginPath();
ctx.rotate((30 * Math.PI / 180) * (hour + m / 60 + s / 3600));
ctx.lineWidth = 5;
ctx.moveTo(0, 0);
ctx.lineTo(60, 0);
ctx.strokeStyle = "#000000";
ctx.stroke();
ctx.restore();
ctx.save();
//画分针
ctx.beginPath();
ctx.rotate((6 * Math.PI / 180) * (m + s / 60));
ctx.lineWidth = 3;
ctx.moveTo(0, 0);
ctx.lineTo(75, 0);
ctx.strokeStyle = "#1ca112";
ctx.stroke();
ctx.restore();
ctx.save();
//画秒针
ctx.beginPath();
ctx.rotate((6 * Math.PI / 180) * s);
ctx.lineWidth = 1;
ctx.moveTo(0, 0);
ctx.lineTo(90, 0);
ctx.strokeStyle = "#ff6b08";
ctx.stroke();
ctx.restore();
ctx.save();
//画外圈
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = "#fc4e19";
ctx.arc(0, 0, 125, 0, 2 * Math.PI);
ctx.stroke();
ctx.restore();
ctx.save();
//返回到初始化状态
ctx.restore();
ctx.restore();
}
//页面加载事件
window.onload = function() {
//每秒钟绘制一次时钟
setInterval(drawClock, 1000);
};
</script>
</body>
</html>

总结:

有几个方法需要注意:

1,ctx.save();ctx.restore();两个方法用于复杂图形的绘画,

2,ctx.translate(140, 140);将(140,140)设为相对参考原点(0,0)

3,ctx.rotate(-Math.PI / 2);旋转角度,因为0°角是右边,我们需要0点时候角度是-90°,所以将角度旋转逆时针90°

4,setInterval(drawClock, 1000); 这个是每秒中重载一次绘制函数,其实把1000设置成1000以下仍然是这个效果,因为重绘的依据是根据时间now来得到m,s,与这个setInterval(drawClock, 1000);的重绘时间没关系,

h5+canvas绘制动画时钟

原文:http://www.cnblogs.com/hujiawei/p/5770052.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!