純Shading Language繪製HTML5時鐘

圖撲軟體發表於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實現程式碼如下:

#ifdef GL_ES
precision mediump float;
#endif

uniform float time;
uniform vec2 resolution;

float pi = 3.1415926; 
float tau = pi * 2.0;

vec2 Rotate(vec2 uv,float angle);

float Circle(vec2 uv,float r);
float Rect(vec2 uv,vec2 size,float r);
float Line(vec2 uv,vec2 start,vec2 end,float r);
float Merge(float a,float b);
float Outline(float a,float r);

vec3 Blend(vec3 backColor, vec3 shapeColor, float shape);

float SecStep(float x); 

void main( void ) 
{
		vec2 res = resolution / resolution.y;
		vec2 uv = ( gl_FragCoord.xy / resolution.y );
		uv -= res / 2.0;                                       

		float secAng = (SecStep(time) / 60.0) * tau;
		float minAng = (time / 3600.0) * tau;
		float hourAng = (time / 43200.0) * tau;

		float clockFace = Circle(uv, 0.45);
		float clockTrim = Outline(clockFace, 0.01);

		vec2 secDomain = Rotate(uv, secAng); 
		float clockSec = Line(secDomain, vec2(0.0, -0.15), vec2(0.0, 0.35), 0.001);
		clockSec = Merge(clockSec, Circle(uv, 0.01));
		clockSec = Merge(clockSec, Rect(secDomain - vec2(0.0, -0.08), vec2(0.012, 0.07), 0.0));

		float clockMin = Line(Rotate(uv, minAng), vec2(0.0,-0.08), vec2(0.0, 0.35), 0.005);
		float clockHour = Line(Rotate(uv, hourAng), vec2(0.0,-0.05), vec2(0.0,0.3), 0.007);
		clockHour = Merge(clockHour, Circle(uv, 0.02));

		float tickMarks = 1.0;
		vec2 tickDomain = uv;
		for(int i = 0;i < 60;i++)
		{
			tickDomain = Rotate(tickDomain, tau / 60.0);
			vec2 size = (mod(float(i + 1), 5.0) == 0.0) ? vec2(0.08, 0.01) : vec2(0.04, 0.002); 
			tickMarks = Merge(tickMarks, Rect(tickDomain - vec2(0.38, 0.0), size, 0.0));
		}

		vec3 faceColor = mix(vec3(1.0, 1.0, 0.0), vec3(1.0, 1.0, 1.0), uv.x+0.5); 
		vec3 trimColor = mix(vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0), uv.y + 0.5); 
		vec3 secColor = vec3(1.0, 0.0, 0.0); 
		vec3 handColor = vec3(0.0, 0.0, 0.0);

		vec3 color = mix(vec3(1.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0), uv.y+0.5);
		color = Blend(color, faceColor, clockFace);
		color = Blend(color, trimColor, clockTrim);
		color = Blend(color, trimColor, tickMarks);                    
		color = Blend(color, handColor, clockHour);
		color = Blend(color, handColor, clockMin);
		color = Blend(color, secColor, clockSec);	

		gl_FragColor = vec4(color, 1.0);
}
float SecStep(float x)
{
	float interp = smoothstep(0.80, 1.0, mod(x, 1.0));
	return floor(x) + interp + (sin(interp * pi)) ;
}            
float Line(vec2 uv,vec2 start,vec2 end,float r)
{
	return Rect(uv-(end+start)/2.0, vec2(r, end.y - start.y), r);
}
float Rect(vec2 uv,vec2 size,float r)
{
	return length(uv - clamp(uv, -size/2.0, size/2.0)) - r;	
}            
vec2 Rotate(vec2 uv,float angle)
{
	return mat2(cos(angle), sin(angle),-sin(angle), cos(angle)) * uv;
}
float Circle(vec2 uv,float r)
{
	return length(uv) - r;	
}
float Merge(float a,float b)
{
	return min(a, b);	
}
float Outline(float a,float r)
{
	return abs(a) - r;	
}
vec3 Blend(vec3 backColor, vec3 shapeColor, float shape)
{       
	return mix(shapeColor, backColor, smoothstep(0.0, 0.005, shape));
}

 HT for Web中《向量手冊》中自定義繪製的clock例子實現程式碼如下:

function init() {
	dataModel = new ht.DataModel();
	graphView = new ht.graph.GraphView(dataModel);
	view = graphView.getView();

	view.className = 'main';
	document.body.appendChild(view);
	window.addEventListener('resize', function(e) {
		graphView.invalidate();
	}, false);

	ht.Default.setCompType('clock-face', function(g, rect, comp, data, view) {
		var cx = rect.x + rect.width / 2;
		var cy = rect.y + rect.height / 2;
		var theta = 0;
		var r = Math.min(rect.width, rect.height)/2 * 0.92;
		
		g.strokeStyle = "#137";
		for (var i = 0; i < 60; i++) {                        
			g.beginPath();
			g.arc(
				cx + Math.cos(theta) * r, 
				cy + Math.sin(theta) * r, 
				i % 5 === 0 ? 4 : 1, 
				0, Math.PI * 2, true);
			g.closePath();
			g.lineWidth = i % 5 === 0 ? 2 : 1;
			g.stroke();
			theta = theta + (6 * Math.PI / 180);
		}
	});

	ht.Default.setImage('clock', {
		width: 500,
		height: 500,
		comps: [
			{
				type: 'circle',
				relative: true,
				rect: [0, 0, 1, 1],
				background: 'yellow',
				gradient: 'linear.northeast'
			},
			{
				type: 'clock-face',
				relative: true,
				rect: [0, 0, 1, 1]
			},
			{
				type: function(g, rect, comp, data, view) {
					// get current time
					var date = data.a('date');
					if(!date){
						return;
					}
					
					var hours = date.getHours();
					var minutes = date.getMinutes();
					var seconds = date.getSeconds();
					hours = hours > 12 ? hours - 12 : hours;
					var hour = hours + minutes / 60;
					var minute = minutes + seconds / 60;
					var clockRadius = 250;

					// save current context
					g.save();

					g.translate(clockRadius, clockRadius);
					g.beginPath();

					// draw numbers
					g.font = '36px Arial';
					g.fillStyle = '#000';
					g.textAlign = 'center';
					g.textBaseline = 'middle';
					for (var n = 1; n <= 12; n++) {
						var theta = (n - 3) * (Math.PI * 2) / 12;
						var x = clockRadius * 0.75 * Math.cos(theta);
						var y = clockRadius * 0.75 * Math.sin(theta);
						g.fillText(n, x, y);
					}

					// draw hour
					g.save();
					var theta = (hour - 3) * 2 * Math.PI / 12;
					g.rotate(theta);
					g.beginPath();
					g.moveTo(-15, -5);
					g.lineTo(-15, 5);
					g.lineTo(clockRadius * 0.5, 1);
					g.lineTo(clockRadius * 0.5, -1);
					g.fill();
					g.restore();

					// draw minute
					g.save();
					var theta = (minute - 15) * 2 * Math.PI / 60;
					g.rotate(theta);
					g.beginPath();
					g.moveTo(-15, -4);
					g.lineTo(-15, 4);
					g.lineTo(clockRadius * 0.8, 1);
					g.lineTo(clockRadius * 0.8, -1);
					g.fill();
					g.restore();

					// draw second
					g.save();
					var theta = (seconds - 15) * 2 * Math.PI / 60;
					g.rotate(theta);
					g.beginPath();
					g.moveTo(-15, -3);
					g.lineTo(-15, 3);
					g.lineTo(clockRadius * 0.9, 1);
					g.lineTo(clockRadius * 0.9, -1);
					g.fillStyle = '#0f0';
					g.fill();
					g.restore();

					g.restore();
				}
			}
		]
	});

	var node = new ht.Node();
	node.setPosition(150, 150);
	node.setSize(250, 250);
	node.setImage('clock');
	node.a('date', new Date());
	node.s('image.stretch', 'centerUniform');
	dataModel.add(node);

	graphView.setEditable(true);
	
	setInterval(function(){
		node.a('date', new Date());
	}, 1000);
}

 

相關文章