HTML5 canvas 画图


<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>HTML5--时钟</title> </head> <body> <canvas id="clock" width="500" height="500"></canvas> <script> var clock = document.getElementById("clock"); var cxt = clock.getContext("2d"); function drawclock() { var now = new Date(); var sec = now.getSeconds(); var min = now.getMinutes(); var hour = now.getHours(); if (hour > 12) hour -= 12;//将24小时改为12小时 hour += min / 60; //获取浮点小时(小时+分钟转换为小时) //清除画布 cxt.clearRect(0, 0, 500, 500); //画表盘 cxt.lineWidth = 10; cxt.strokeStyle = "blue"; cxt.beginPath(); cxt.arc(250, 250, 200, 0, 360, false); cxt.closePath(); cxt.stroke(); //画刻度 //时刻度 for (var i = 0; i < 12; i++) { cxt.save(); cxt.lineWidth = 7;//设置时钟线粗细 cxt.strokeStyle = "#000";//设置时钟线的颜色 cxt.translate(250, 250);//设置旋转原点 cxt.rotate(i * 30 * Math.PI / 180);//角度*Math.PI/180 cxt.beginPath(); cxt.moveTo(0, -180); cxt.lineTo(0, -195); cxt.closePath(); cxt.stroke(); cxt.restore(); } //分刻度 for (var i = 0; i < 60; i++) { cxt.save(); cxt.lineWidth = 4;//设置时钟线粗细 cxt.strokeStyle = "#000";//设置时钟线的颜色 cxt.translate(250, 250);//设置旋转原点 cxt.rotate(i * 6 * Math.PI / 180);//角度*Math.PI/180 cxt.beginPath();//开始路径 cxt.moveTo(0, -188);//开始点 cxt.lineTo(0, -193);//结束点 cxt.closePath();//闭合路径 cxt.stroke(); cxt.restore(); } cxt.fillStyle = "#FFF"; //秒针 cxt.save(); cxt.lineWidth = 8; cxt.strokeStyle = "red"; cxt.translate(250, 250); cxt.rotate(sec * 6 * Math.PI / 180); cxt.beginPath(); cxt.moveTo(4, 10) cxt.lineTo(1, -165); cxt.lineTo(0, -167); cxt.lineTo(-1, -165); cxt.lineTo(-4, 10); cxt.lineTo(0, 15); cxt.closePath(); cxt.stroke(); cxt.fill(); cxt.restore(); //分针 cxt.save(); cxt.lineWidth = 8; cxt.strokeStyle = "yellow"; cxt.translate(250, 250); cxt.rotate(min*6 * Math.PI / 180); cxt.beginPath(); cxt.moveTo(3, 10) cxt.lineTo(1, -135); cxt.lineTo(0, -137); cxt.lineTo(-1, -135); cxt.lineTo(-3, 10); cxt.lineTo(0, 14); cxt.closePath(); cxt.stroke(); cxt.fill(); cxt.restore(); //时针 cxt.save(); cxt.lineWidth = 8; cxt.strokeStyle = "blue"; cxt.translate(250, 250); cxt.rotate(hour * 30 * Math.PI / 180); cxt.beginPath(); cxt.moveTo(2, 10) cxt.lineTo(1, -110); cxt.lineTo(0, -112); cxt.lineTo(-1, -110); cxt.lineTo(-2, 10); cxt.lineTo(0, 13); cxt.closePath(); cxt.stroke(); cxt.fill(); cxt.restore(); //画圆心 cxt.lineWidth = 4; cxt.beginPath(); cxt.arc(250, 250, 5, 0, 360, false); cxt.closePath(); cxt.strokeStyle = "#000"; cxt.stroke(); cxt.fillStyle = "#999"; cxt.fill(); cxt.restore(); } drawclock(); //周期函数 setInterval(drawclock, 1000); </script> </body> </html>

  

posted @ 2013-09-07 14:51  笨小蛋  阅读(273)  评论(0)    收藏  举报