纯Shading Language绘制HTML5时钟

By | 2014年12月31日

今天是2014年的最后一天,这个时刻总会让人想起时钟,再过几个小时地球人都要再老了一岁,于是搞个HTML5版的时钟就是我们今天要完成的任务,实现HTML5的时钟绘制一般会采用三种方式,第一种采用CSS的实现方式,例如 http://www.css-tricks.com/examples/CSS3Clock/ ;第二种采用SVG的实现方式,例如 http://www.css-tricks.com/examples/CSS3Clock/;第三种采用Cavnas的2D绘制方式,如HT for Web中《矢量手册》中自定义绘制的clock例子,HT的例子的实现效果如下,其实现代码附在本文的最后部分。

Screen Shot 2014-12-31 at 8.19.17 PM

以上三种方式都是较容易理解的实现方式,今天我们将采用的则是较为少见的WebGL纯Shading Language实现方式,这种方式极其高效,毕竟我们采用的是可利用GPU硬件加速的WebGL技术,CPU代码角度看仅有两个三角形的绘制,真正表盘的绘制逻辑完全在GPU对两个三角形进行Fragment Shading时实现。

Screen Shot 2014-12-31 at 8.08.48 PM

可通过这里 http://js.do/hightopo/glsl-clock 玩玩最后的实现效果以及实现代码,采用GLSL的实现最重要的就是决定当前坐标位置的gl_FragColor的颜色,我们将始终分为表盘、外圈、刻度、时针、分针和秒针几个部分,代码后部分的留个连续Blend代码相当于逐层绘制的逻辑,以下几个函数技术点说明:

  • Rect函数中的clamp(uv, -size/2.0, size/2.0))是我们决定点是否在矩形区域的技巧
  • 函数Rotate(vec2 uv,float angle)将坐标点旋转到水平或垂直位置方便我们确定Rect和Line参数进行对比
  • Blend函数mix(shapeColor, backColor, smoothstep(0.0, 0.005, shape))是常用的混合mix和smoothstep达到更好处理边缘平滑效果GLSL常用技巧

为了说明mix和smoothstep的融合效果,我搞了个 http://js.do/hightopo/glsl-smooth-clrcle 的例子,你可以尝试去掉#define SMOOTH后边缘锯齿较明显的问题,也可以调节smoothstep(0.49, 0.5, d)的0.49为0.3等较小的参数体验渐进的效果,以下为几种效果的综合对比

Screen Shot 2014-12-31 at 7.09.28 PM

GLSL的Fragment Shader实现代码如下:

001#ifdef GL_ES
002precision mediump float;
003#endif
004 
005uniform float time;
006uniform vec2 resolution;
007 
008float pi = 3.1415926;
009float tau = pi * 2.0;
010 
011vec2 Rotate(vec2 uv,float angle);
012 
013float Circle(vec2 uv,float r);
014float Rect(vec2 uv,vec2 size,float r);
015float Line(vec2 uv,vec2 start,vec2 end,float r);
016float Merge(float a,float b);
017float Outline(float a,float r);
018 
019vec3 Blend(vec3 backColor, vec3 shapeColor, float shape);
020 
021float SecStep(float x);
022 
023void main( void )
024{
025        vec2 res = resolution / resolution.y;
026        vec2 uv = ( gl_FragCoord.xy / resolution.y );
027        uv -= res / 2.0;                                      
028 
029        float secAng = (SecStep(time) / 60.0) * tau;
030        float minAng = (time / 3600.0) * tau;
031        float hourAng = (time / 43200.0) * tau;
032 
033        float clockFace = Circle(uv, 0.45);
034        float clockTrim = Outline(clockFace, 0.01);
035 
036        vec2 secDomain = Rotate(uv, secAng);
037        float clockSec = Line(secDomain, vec2(0.0, -0.15), vec2(0.0, 0.35), 0.001);
038        clockSec = Merge(clockSec, Circle(uv, 0.01));
039        clockSec = Merge(clockSec, Rect(secDomain - vec2(0.0, -0.08), vec2(0.012, 0.07), 0.0));
040 
041        float clockMin = Line(Rotate(uv, minAng), vec2(0.0,-0.08), vec2(0.0, 0.35), 0.005);
042        float clockHour = Line(Rotate(uv, hourAng), vec2(0.0,-0.05), vec2(0.0,0.3), 0.007);
043        clockHour = Merge(clockHour, Circle(uv, 0.02));
044 
045        float tickMarks = 1.0;
046        vec2 tickDomain = uv;
047        for(int i = 0;i < 60;i++)
048        {
049            tickDomain = Rotate(tickDomain, tau / 60.0);
050            vec2 size = (mod(float(i + 1), 5.0) == 0.0) ? vec2(0.08, 0.01) : vec2(0.04, 0.002);
051            tickMarks = Merge(tickMarks, Rect(tickDomain - vec2(0.38, 0.0), size, 0.0));
052        }
053 
054        vec3 faceColor = mix(vec3(1.0, 1.0, 0.0), vec3(1.0, 1.0, 1.0), uv.x+0.5);
055        vec3 trimColor = mix(vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), uv.y + 0.5);
056        vec3 secColor = vec3(1.0, 0.0, 0.0);
057        vec3 handColor = vec3(0.0, 0.0, 0.0);
058 
059        vec3 color = mix(vec3(1.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0), uv.y+0.5);
060        color = Blend(color, faceColor, clockFace);
061        color = Blend(color, trimColor, clockTrim);
062        color = Blend(color, trimColor, tickMarks);                   
063        color = Blend(color, handColor, clockHour);
064        color = Blend(color, handColor, clockMin);
065        color = Blend(color, secColor, clockSec);  
066 
067        gl_FragColor = vec4(color, 1.0);
068}
069float SecStep(float x)
070{
071    float interp = smoothstep(0.80, 1.0, mod(x, 1.0));
072    return floor(x) + interp + (sin(interp * pi)) ;
073}           
074float Line(vec2 uv,vec2 start,vec2 end,float r)
075{
076    return Rect(uv-(end+start)/2.0, vec2(r, end.y - start.y), r);
077}
078float Rect(vec2 uv,vec2 size,float r)
079{
080    return length(uv - clamp(uv, -size/2.0, size/2.0)) - r;
081}           
082vec2 Rotate(vec2 uv,float angle)
083{
084    return mat2(cos(angle), sin(angle),-sin(angle), cos(angle)) * uv;
085}
086float Circle(vec2 uv,float r)
087{
088    return length(uv) - r; 
089}
090float Merge(float a,float b)
091{
092    return min(a, b);  
093}
094float Outline(float a,float r)
095{
096    return abs(a) - r; 
097}
098vec3 Blend(vec3 backColor, vec3 shapeColor, float shape)
099{      
100    return mix(shapeColor, backColor, smoothstep(0.0, 0.005, shape));
101}

HT for Web中《矢量手册》中自定义绘制的clock例子实现代码如下:

001function init() {
002    dataModel = new ht.DataModel();
003    graphView = new ht.graph.GraphView(dataModel);
004    view = graphView.getView();
005 
006    view.className = 'main';
007    document.body.appendChild(view);
008    window.addEventListener('resize', function(e) {
009        graphView.invalidate();
010    }, false);
011 
012    ht.Default.setCompType('clock-face', function(g, rect, comp, data, view) {
013        var cx = rect.x + rect.width / 2;
014        var cy = rect.y + rect.height / 2;
015        var theta = 0;
016        var r = Math.min(rect.width, rect.height)/2 * 0.92;
017         
018        g.strokeStyle = "#137";
019        for (var i = 0; i < 60; i++) {                       
020            g.beginPath();
021            g.arc(
022                cx + Math.cos(theta) * r,
023                cy + Math.sin(theta) * r,
024                i % 5 === 0 ? 4 : 1,
025                0, Math.PI * 2, true);
026            g.closePath();
027            g.lineWidth = i % 5 === 0 ? 2 : 1;
028            g.stroke();
029            theta = theta + (6 * Math.PI / 180);
030        }
031    });
032 
033    ht.Default.setImage('clock', {
034        width: 500,
035        height: 500,
036        comps: [
037            {
038                type: 'circle',
039                relative: true,
040                rect: [0, 0, 1, 1],
041                background: 'yellow',
042                gradient: 'linear.northeast'
043            },
044            {
045                type: 'clock-face',
046                relative: true,
047                rect: [0, 0, 1, 1]
048            },
049            {
050                type: function(g, rect, comp, data, view) {
051                    // get current time
052                    var date = data.a('date');
053                    if(!date){
054                        return;
055                    }
056                     
057                    var hours = date.getHours();
058                    var minutes = date.getMinutes();
059                    var seconds = date.getSeconds();
060                    hours = hours > 12 ? hours - 12 : hours;
061                    var hour = hours + minutes / 60;
062                    var minute = minutes + seconds / 60;
063                    var clockRadius = 250;
064 
065                    // save current context
066                    g.save();
067 
068                    g.translate(clockRadius, clockRadius);
069                    g.beginPath();
070 
071                    // draw numbers
072                    g.font = '36px Arial';
073                    g.fillStyle = '#000';
074                    g.textAlign = 'center';
075                    g.textBaseline = 'middle';
076                    for (var n = 1; n <= 12; n++) {
077                        var theta = (n - 3) * (Math.PI * 2) / 12;
078                        var x = clockRadius * 0.75 * Math.cos(theta);
079                        var y = clockRadius * 0.75 * Math.sin(theta);
080                        g.fillText(n, x, y);
081                    }
082 
083                    // draw hour
084                    g.save();
085                    var theta = (hour - 3) * 2 * Math.PI / 12;
086                    g.rotate(theta);
087                    g.beginPath();
088                    g.moveTo(-15, -5);
089                    g.lineTo(-15, 5);
090                    g.lineTo(clockRadius * 0.5, 1);
091                    g.lineTo(clockRadius * 0.5, -1);
092                    g.fill();
093                    g.restore();
094 
095                    // draw minute
096                    g.save();
097                    var theta = (minute - 15) * 2 * Math.PI / 60;
098                    g.rotate(theta);
099                    g.beginPath();
100                    g.moveTo(-15, -4);
101                    g.lineTo(-15, 4);
102                    g.lineTo(clockRadius * 0.8, 1);
103                    g.lineTo(clockRadius * 0.8, -1);
104                    g.fill();
105                    g.restore();
106 
107                    // draw second
108                    g.save();
109                    var theta = (seconds - 15) * 2 * Math.PI / 60;
110                    g.rotate(theta);
111                    g.beginPath();
112                    g.moveTo(-15, -3);
113                    g.lineTo(-15, 3);
114                    g.lineTo(clockRadius * 0.9, 1);
115                    g.lineTo(clockRadius * 0.9, -1);
116                    g.fillStyle = '#0f0';
117                    g.fill();
118                    g.restore();
119 
120                    g.restore();
121                }
122            }
123        ]
124    });
125 
126    var node = new ht.Node();
127    node.setPosition(150, 150);
128    node.setSize(250, 250);
129    node.setImage('clock');
130    node.a('date', new Date());
131    node.s('image.stretch', 'centerUniform');
132    dataModel.add(node);
133 
134    graphView.setEditable(true);
135     
136    setInterval(function(){
137        node.a('date', new Date());
138    }, 1000);
139}

One thought on “纯Shading Language绘制HTML5时钟

  1. Pingback: 纯Shading Language绘制飞机火焰效果-紫金星

Comments are closed.