JavaScript动态时钟
继续玩JavaScript CanvasRenderingContext2D。前面画出来的都是“死”的,下面结合前面两个例子做一个“动”态时钟。当然还是得先了解一下即将用到的一些新属性及方法。
方法
save():
将当前图形信息存储在栈中。
restore():
从栈中取出图形信息并应用。
clearRect(float x, float y, float width, float height):
清空指定区域的图像并透明化。
translate(float dx, float dy):
为画布的变换矩阵添加水平的和垂直的偏移。参数 dx 和 dy 添加给后续定义路径中的所有点。
scale(float sx, float sy):
横纵缩放。
rotate(angle):
旋转,angle为弧度数。
lineTo(float x, float y):
指定线条终点坐标。
fill():
填充图形。
属性
lineWidth:
线条宽度
lineCap:
指定线段如何结束。只有绘制较宽线段时,它才有效。这个属性的合法值如下表所示。默认值是:”butt”。
“butt” 这个默认值指定了线段应该没有线帽。线条的末点是平直的而且和线条的方向正交,这条线段在其端点之外没有扩展。
“round” 这个值指定了线段应该带有一个半圆形的线帽,半圆的直径等于线段的宽度,并且线段在端点之外扩展了线段宽度的一半。
“square” 这个值表示线段应该带有一个矩形线帽。这个值和 “butt” 一样,但是线段扩展了自己的宽度的一半。
其它方法及属性可参见及。
下面给出代码:
function clock(){ var now = new Date(); var ctx = document.getElementById('clock').getContext('2d'); //保存状态,将当前状态压栈 ctx.save(); //清理图像 ctx.clearRect(0,0,150,150); //已(75, 75)为原点,将图像复制 ctx.translate(75, 75); //横纵比 ctx.scale(0.5, 0.5); //逆转90° ctx.rotate(-Math.PI/2); //设置线条颜色 ctx.strokeStyle = "black"; //设置填充颜色 ctx.fillStyle = "white"; //设置线条宽度 ctx.lineWidth = 8; //设置线边角为圆角 ctx.lineCap = "round"; //保存状态,将当前状态压栈 ctx.save(); //画出12个时刻 for (var i=0;i<12;i++){ //以当前原点为圆心 ctx.beginPath(); //旋转30° ctx.rotate(Math.PI/6); //以圆心外100像素处为起点,120像素处为终点画线 ctx.moveTo(100,0); ctx.lineTo(120,0); //画出这条路线 ctx.stroke(); } //出栈,将取出的状态作为当前状态 ctx.restore(); //再将状态压栈,保存起来 ctx.save(); //设置线条宽度 ctx.lineWidth = 5; //画出60个分钟 for (i=0;i<60;i++){ //因为时针就是每五分钟的点了,所以跳过不画了 if (i%5!=0) { ctx.beginPath(); ctx.moveTo(117,0); ctx.lineTo(120,0); ctx.stroke(); } //旋转6° ctx.rotate(Math.PI/30); } //出栈,将取出的状态作为当前状态 ctx.restore(); //取出当前秒 var sec = now.getSeconds(); //取出当前分 var min = now.getMinutes(); //取出当前时 var hr = now.getHours(); //判断是否是24小时计时法,是则减12 hr = hr>=12 ? hr-12 : hr; //再将状态压栈,保存起来 ctx.save(); // 画出时针 //时针转向当前位置 ctx.rotate( hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec ); //设置时针宽度 ctx.lineWidth = 14; //以当前原点为圆心 ctx.beginPath(); //反向延长20个像素 ctx.moveTo(-20,0); ctx.lineTo(80,0); //画线 ctx.stroke(); ctx.restore(); //画分针 ctx.save(); ctx.rotate( (Math.PI/30)*min + (Math.PI/1800)*sec ) ctx.lineWidth = 10; ctx.strokeStyle = 'blue'; ctx.beginPath(); ctx.moveTo(-28,0); ctx.lineTo(112,0); ctx.stroke(); ctx.restore(); //画秒针 ctx.save(); ctx.rotate(sec * Math.PI/30); ctx.strokeStyle = "red"; ctx.fillStyle = "red"; ctx.lineWidth = 6; ctx.beginPath(); ctx.moveTo(-30,0); ctx.lineTo(120,0); ctx.stroke(); ctx.beginPath(); ctx.arc(0,0,10,0,Math.PI*2,true); ctx.fill(); ctx.beginPath(); ctx.arc(90,0,10,0,Math.PI*2,true); ctx.stroke(); ctx.fillStyle = "black"; ctx.arc(0,0,3,0,Math.PI*2,true); ctx.fill(); ctx.restore(); //加一个表盘 ctx.beginPath(); ctx.lineWidth = 14; ctx.strokeStyle = 'gray'; ctx.arc(0,0,142,0,Math.PI*2,true); ctx.stroke(); ctx.restore(); }
在浏览器里面看看吧 !咦!为什么没有动呢?这可不是GIF图片啊!怎么动呢?
再加一段如上代码进去,然后调用initClock()方法,现在再看看,动了吧。其实每次看到的都是一张静止的图片,只是每隔一秒将当前的时间以钟表的样子画上去而已。
转载原创文章请注明,转载自:Neeke[]
本文链接:
除非另有声明,本网站采用授权。
您可以自由: 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 创作演绎作品
惟须遵守下列条件: 署名 — 您必须按照作者或者许可人指定的方式对作品进行署名。