HTML5学习随笔(1)
2013-05-24 13:30 Barret李靖 阅读(440) 评论(0) 编辑 收藏 举报关键词:HTML5, canvas, 时钟, 入门
学习内容:通过制作canvas时钟了解canvas主要方法的使用
DEMO:http://qianduannotes.sinaapp.com/test/canvas.html
时钟设计
1. Design:
2. colors:
表盘:#ABCDEF dialColor
秒钟:red sColor
秒钟原点: gray sDotColor
3. size:
画布:400*400 panel
表盘:R = 160 dialR
时针刻度:5*7 hW hH
分针刻度:5*3 mW mH
时针:10*130 hHW hHH
分针:5*147 mHW mHH
秒钟:3*160 sHW sHH
秒钟原点:r = 5 sDotR
4. position
表盘中心:200*200 dialT dialL
秒钟原点中心: 120 sDotP
代码
var clock = document.getElementById('clock'); var cxt = clock.getContext('2d'); //设置2D制图环境 function draw(){ //清楚画布 cxt.clearRect(0, 0, 400, 400); var now = new Date(); var sec = now.getSeconds(); var min = now.getMinutes(); var hour = now.getHours(); //小时必须是浮点类型(小时+分数转换成小时) hour = hour+min/60; hour = hour>12?hour-12:hour; //表盘 cxt.beginPath(); cxt.lineWidth = 10; cxt.strokeStyle = "#ABCDEF"; cxt.arc(200, 200, 160, 0, 360, false); cxt.stroke(); cxt.closePath(); //刻度 //时刻度 for(var i = 0;i<12;i++){ cxt.save(); cxt.lineWidth = 7; cxt.strokeStyle = "#000000"; cxt.translate(200, 200); cxt.rotate(i*30*Math.PI/180); //角度*Math.PI/180 cxt.beginPath(); cxt.moveTo(0, -140); cxt.lineTo(0, -155); cxt.closePath(); cxt.stroke(); cxt.restore(); } //分刻度 for(var j = 0;j<60;j++){ cxt.save(); cxt.lineWidth = 3; cxt.strokeStyle = "#000"; cxt.translate(200, 200); cxt.rotate(j*6*Math.PI/180); cxt.beginPath(); cxt.moveTo(0, -150); cxt.lineTo(0, -155); cxt.closePath(); cxt.stroke(); cxt.restore(); } //时针 cxt.save(); cxt.lineWidth = 10; cxt.strokeStyle = "#000"; cxt.beginPath(); cxt.translate(200, 200); cxt.rotate(hour*30*Math.PI/180); cxt.moveTo(0, -120); cxt.lineTo(0, 10); cxt.closePath(); cxt.stroke(); cxt.restore(); //分针 cxt.save(); cxt.lineWidth = 5; cxt.strokeStyle = "#000"; cxt.translate(200, 200); cxt.rotate(min*6*Math.PI/180); cxt.beginPath(); cxt.moveTo(0, -135); cxt.lineTo(0, 12); cxt.closePath(); cxt.stroke(); cxt.restore(); //秒针 cxt.save(); cxt.lineWidth = 3; cxt.strokeStyle = "red"; cxt.translate(200, 200); cxt.rotate(sec*6*Math.PI/180); cxt.beginPath(); cxt.moveTo(0, -140); cxt.lineTo(0, 20); cxt.closePath(); cxt.stroke(); //画出时针,分针的交叉点 cxt.beginPath(); cxt.arc(0, 0, 5, 0, 360, false); cxt.closePath(); cxt.fillStyle = "gray"; cxt.fill(); cxt.stroke(); //秒针的原点 cxt.beginPath(); cxt.arc(0, -120, 5, 0, 360, false); cxt.closePath(); cxt.fillStyle = "gray"; cxt.fill(); cxt.stroke(); cxt.restore(); } //使用setInterval(代码,毫秒时间)函数让时针动起来 draw(); setInterval(draw, 1000);
. .
版权声明: 署名-非商业性使用-禁止演绎 3.0 国际(CC BY-NC-ND 3.0)