使用 html5 Canvas 标签 画一个时钟
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>canvas</title>
- <style>
- body{background: black;}
- #c1{background: white;
- }
- </style>
- <script>
- window.onload=function () {
- var oc=document.getElementById("c1");
- var ogc=oc.getContext("2d");
- // ogc.moveTo(200,200);
- // ogc.arc(200,200,150,0,90*Math.PI/180,false);
- // ogc.stroke();
- function toDraw() {
- var x=200;
- var y=200;
- var r=150;
- ogc.clearRect(0,0,ogc.width,ogc.height);
- var oDate=new Date();
- var oHours=oDate.getHours();
- var oMin=oDate.getMinutes();
- var oSec=oDate.getSeconds();
- var oHoursValue=(-90+oHours*30+oMin/2)*Math.PI/180;
- var oMinValue=(-90+oMin*6)*Math.PI/180;
- var oSecValue=(-90+oSec*6)*Math.PI/180;
- // ogc.moveTo(x,y);
- // ogc.arc(x,y,r,0,6*Math.PI/180,false);
- // ogc.moveTo(x,y);
- // ogc.arc(x,y,r,6*Math.PI/180,12*Math.PI/180,false);
- ogc.beginPath();
- for (var i=0;i<60;i++){
- ogc.moveTo(x,y);
- ogc.arc(x,y,r,6*i*Math.PI/180,6*(i+1)*Math.PI/180,false);
- }
- ogc.closePath();
- ogc.stroke();
- ogc.fillStyle="white";
- ogc.beginPath();
- ogc.moveTo(x,y);
- ogc.arc(x,y,r*19/20,0,360*Math.PI/180,false);
- ogc.closePath();
- ogc.fill();
- ogc.lineWidth=3;
- ogc.beginPath();
- for (var i=0;i<12;i++){
- ogc.moveTo(x,y);
- ogc.arc(x,y,r,30*i*Math.PI/180,30*(i+1)*Math.PI/180,false);
- }
- ogc.closePath();
- ogc.stroke();
- ogc.fillStyle="white";
- ogc.beginPath();
- ogc.moveTo(x,y);
- ogc.arc(x,y,r*18/20,0,360*Math.PI/180,false);
- ogc.closePath();
- ogc.fill();
- ogc.lineWidth=5;
- ogc.beginPath();
- ogc.moveTo(x,y);
- ogc.arc(x,y,r*10/20,oHoursValue,oHoursValue,false);
- ogc.closePath();
- ogc.stroke();
- ogc.lineWidth=3;
- ogc.beginPath();
- ogc.moveTo(x,y);
- ogc.arc(x,y,r*14/20,oMinValue,oMinValue,false);
- ogc.closePath();
- ogc.stroke();
- ogc.lineWidth=1;
- ogc.beginPath();
- ogc.moveTo(x,y);
- ogc.arc(x,y,r*19/20,oSecValue,oSecValue,false);
- ogc.closePath();
- ogc.stroke();
- }
- setInterval(toDraw,1000);
- toDraw();
- }
- </script>
- </head>
- <body>
- <canvas id="c1" width="400" height="400"></canvas>
- </body>
- </html>
- <canvas></canvas > 标签可以像所有的 dom 对象一样它有自己本身的属性, 方法和事件, 其中就有绘图的方法, js 能够调用它来进行绘图
代码中 context 是一个封装了很多绘图功能的对象 var context =canvas.getContext("2d");
canvas 元素绘制图像的时候有两种方法, 分别是
- context.fill()// 填充
- context.stroke()// 绘制边框
来源: http://www.qdfuns.com/article/42658/81fd0ba1c33652b5ecaa45faa21570de.html