-
Notifications
You must be signed in to change notification settings - Fork 58
/
index.html
313 lines (248 loc) · 13.5 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
<!DOCTYPE html>
<html>
<head>
<title>TinySDF demo</title>
<meta charset="utf8" />
<style>
body { font: 14px/1 Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
#container { width: 1000px; margin: 0 auto; }
input { width: 880px; }
label { font-weight: bold; width: 90px; display: inline-block; }
a { color: #0af; }
#log { margin: 0; }
</style>
</head>
<body>
<div id="container">
<h1><a href="https://github.com/mapbox/tiny-sdf">TinySDF</a> demo</h1>
<p>
<label>Font size</label> <input id="fontsize" type="range" min="16" max="104" step="8" value="24">
<label>Font weight</label> <input id="fontweight" type="range" min="100" max="900" step="100" value="400">
</p>
<canvas id="canvas" width="1000" height="400"></canvas>
<p id="log"></p>
<p>
<label>Size</label> <input type="range" value="128" step="0.01" min="16" max="256.0" id="scale">
<label>Halo</label> <input type="range" value="0.55" step="0.01" min="0.4" max="0.9" id="halo">
<label>Angle</label> <input type="range" value="0" step="0.01" min="-0.1" max="0.1" id="angle">
<label>Gamma</label> <input type="range" value="2" step="0.01" min="0" max="4" id="gamma">
</p>
<canvas id="canvas2" width="1000" height="100"></canvas>
</div>
<script type="module">
import {mat4} from 'https://cdn.skypack.dev/pin/gl-matrix@v3.3.0-QDHIgv9E54Kj6suUMV0n/mode=imports,min/optimized/gl-matrix.js';
import TinySDF from './index.js';
const chars = '𢄂𡔖城泽材灭逐莫笔亡鲜词圣择寻厂睡博勒烟授诺伦岸奥唐卖俄炸载洛健堂旁宫喝借君禁阴园谋宋避抓荣姑孙逃牙束跳顶玉镇雪午练迫爷篇肉嘴馆遍凡础洞卷坦牛宁纸诸训私庄祖丝翻暴森塔默握戏隐熟骨访弱蒙歌店鬼软典欲萨伙遭盘爸扩盖弄雄稳忘亿刺拥徒姆杨齐赛趣曲刀床迎冰虚玩析窗醒妻透购替塞努休虎扬途侵刑绿兄迅套贸毕唯谷轮库迹尤竞街促延震弃甲伟麻川申缓潜闪售灯针哲络抵朱埃抱鼓植纯夏忍页杰筑折郑贝尊吴秀混臣雅振染盛怒舞圆搞狂措姓残秋培迷诚宽宇猛摆梅毁伸摩盟末乃悲拍丁赵硬麦蒋操耶阻订彩抽赞魔纷沿喊违妹浪汇币丰蓝殊献桌啦瓦莱援译夺汽烧距裁偏符勇触课敬哭懂墙袭召罚侠厅拜巧侧韩冒债曼融惯享戴童犹乘挂奖绍厚纵障讯涉彻刊丈爆乌役描洗玛患妙镜唱烦签仙彼弗症仿倾牌陷鸟轰咱菜闭奋庆撤泪茶疾缘播朗杜奶季丹狗尾仪偷奔珠虫驻孔宜艾桥淡翼恨繁寒伴叹旦愈潮粮缩罢聚径恰挑袋灰捕徐珍幕映裂泰隔启尖忠累炎暂估泛荒偿横拒瑞忆孤鼻闹羊呆厉衡胞零穷舍码赫婆魂灾洪腿胆津俗辩胸晓劲贫仁偶辑邦恢赖圈摸仰润堆碰艇稍迟辆废净凶署壁御奉旋冬矿抬蛋晨伏吹鸡倍糊秦盾杯租骑乏隆诊奴摄丧污渡旗甘耐凭扎抢绪粗肩梁幻菲皆碎宙叔岩荡综爬荷悉蒂返井壮薄悄扫敏碍殖详迪矛霍允幅撒剩凯颗骂赏液番箱贴漫酸郎腰舒眉忧浮辛恋餐吓挺励辞艘键伍峰尺昨黎辈贯侦滑券崇扰宪绕趋慈乔阅汗枝拖墨胁插箭腊粉泥氏彭拔骗凤慧媒佩愤扑龄驱惜豪掩兼跃尸肃帕驶堡届欣惠册储飘桑闲惨洁踪勃宾频仇磨递邪撞拟滚奏巡颜剂绩贡疯坡瞧截燃焦殿伪柳锁逼颇昏劝呈搜勤戒驾漂饮曹朵仔柔俩孟腐幼践籍牧凉牲佳娜浓芳稿竹腹跌逻垂遵脉貌柏狱猜怜惑陶兽帐饰贷昌叙躺钢沟寄扶铺邓寿惧询汤盗肥尝匆辉奈扣廷澳嘛董迁凝慰厌脏腾幽怨鞋丢埋泉涌辖躲晋紫艰魏吾慌祝邮吐狠鉴曰械咬邻赤挤弯椅陪割揭韦悟聪雾锋梯猫祥阔誉筹丛牵鸣沈阁穆屈旨袖猎臂蛇贺柱抛鼠瑟戈牢逊迈欺吨琴衰瓶恼燕仲诱狼池疼卢仗冠粒遥吕玄尘冯抚浅敦纠钻晶岂峡苍喷耗凌敲菌赔涂粹扁亏寂煤熊恭湿循暖糖赋抑秩帽哀宿踏烂袁侯抖夹昆肝擦猪炼恒慎搬纽纹玻渔磁铜齿跨押怖漠疲叛遣兹祭醉拳弥斜档稀捷肤疫肿豆削岗晃吞宏癌肚隶履涨耀扭坛拨沃绘伐堪仆郭牺歼墓雇廉契拼惩捉覆刷劫嫌瓜歇雕闷乳串娃缴唤赢莲霸桃妥瘦搭赴岳嘉舱俊址庞耕锐缝悔邀玲惟斥宅添挖呵讼氧浩羽斤酷掠妖祸侍乙妨贪挣汪尿莉悬唇翰仓轨枚盐览傅帅庙芬屏寺胖璃愚滴疏萧姿颤丑劣柯寸扔盯辱匹俱辨饿蜂哦腔郁溃谨糟葛苗肠忌溜鸿爵鹏鹰笼丘桂滋聊挡纲肌茨壳痕碗穴膀卓贤卧膜毅锦欠哩函';
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const sdfs = {};
// Convert alpha-only to RGBA so we can use `putImageData` for building the composite bitmap
function makeRGBAImageData(alphaChannel, width, height) {
const imageData = ctx.createImageData(width, height);
for (let i = 0; i < alphaChannel.length; i++) {
imageData.data[4 * i + 0] = alphaChannel[i];
imageData.data[4 * i + 1] = alphaChannel[i];
imageData.data[4 * i + 2] = alphaChannel[i];
imageData.data[4 * i + 3] = 255;
}
return imageData;
}
function updateSDF() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const fontSize = +document.getElementById('fontsize').value;
const fontWeight = +document.getElementById('fontweight').value;
const fontStyle = 'normal';
const buffer = Math.ceil(fontSize / 8);
const radius = Math.ceil(fontSize / 3);
const sdf = new TinySDF({fontSize, buffer, radius, fontWeight, fontStyle});
const size = fontSize + buffer * 2;
const now = performance.now();
const codePoints = chars[Symbol.iterator]();
let i = 0;
let codePoint = codePoints.next();
for (let y = 0; y + size <= canvas.height && !codePoint.done; y += size) {
for (let x = 0; x + size <= canvas.width && !codePoint.done; x += size) {
const {data, width, height} = sdf.draw(codePoint.value);
ctx.putImageData(makeRGBAImageData(data, width, height), x, y);
sdfs[codePoint.value] = {x, y};
i++;
codePoint = codePoints.next();
}
}
document.getElementById('log').innerHTML = `${i} characters (${fontSize}px, font-weight: ${fontWeight} with ${buffer}px buffer) rendered in ${Math.round(performance.now() - now)}ms.`;
}
const canvas2 = document.getElementById('canvas2');
if (window.devicePixelRatio > 1) {
canvas2.style.width = `${canvas2.width}px`;
canvas2.style.height = `${canvas2.height}px`;
canvas2.width *= 2;
canvas2.height *= 2;
}
const gl = canvas2.getContext('webgl', {antialias: false});
if (!gl) {
alert('Failed to initialize WebGL');
}
const vertexSource = `
attribute vec2 a_pos;
attribute vec2 a_texcoord;
uniform mat4 u_matrix;
uniform vec2 u_texsize;
varying vec2 v_texcoord;
void main() {
gl_Position = u_matrix * vec4(a_pos.xy, 0, 1);
v_texcoord = a_texcoord / u_texsize;
}`;
const fragmentSource = `
precision mediump float;
uniform sampler2D u_texture;
uniform vec4 u_color;
uniform float u_buffer;
uniform float u_gamma;
varying vec2 v_texcoord;
void main() {
float dist = texture2D(u_texture, v_texcoord).r;
float alpha = smoothstep(u_buffer - u_gamma, u_buffer + u_gamma, dist);
gl_FragColor = vec4(u_color.rgb, alpha * u_color.a);
}`;
const shader = createProgram(gl, vertexSource, fragmentSource);
gl.useProgram(shader.program);
gl.enableVertexAttribArray(shader.a_pos);
gl.enableVertexAttribArray(shader.a_texcoord);
const pMatrix = mat4.create();
mat4.ortho(pMatrix, 0, gl.canvas.width, gl.canvas.height, 0, 0, -1);
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE);
gl.enable(gl.BLEND);
const texture = gl.createTexture();
const vertexBuffer = gl.createBuffer();
const textureBuffer = gl.createBuffer();
const str = '泽材灭逐莫笔亡鲜词圣择寻厂睡博';
function drawText(size) {
const vertexElements = [];
const textureElements = [];
const fontsize = +document.getElementById('fontsize').value;
const buf = fontsize / 8;
const width = fontsize + buf * 2; // glyph width
const height = fontsize + buf * 2; // glyph height
const bx = 0; // bearing x
const by = fontsize / 2 + buf; // bearing y
const advance = fontsize; // advance
const scale = size / fontsize;
const lineWidth = str.length * fontsize * scale;
const pen = {x: canvas2.width / 2 - lineWidth / 2, y: canvas2.height / 2};
for (const codePoint of str) {
const posX = sdfs[codePoint].x; // pos in sprite x
const posY = sdfs[codePoint].y; // pos in sprite y
vertexElements.push(
pen.x + ((bx - buf) * scale), pen.y - by * scale,
pen.x + ((bx - buf + width) * scale), pen.y - by * scale,
pen.x + ((bx - buf) * scale), pen.y + (height - by) * scale,
pen.x + ((bx - buf + width) * scale), pen.y - by * scale,
pen.x + ((bx - buf) * scale), pen.y + (height - by) * scale,
pen.x + ((bx - buf + width) * scale), pen.y + (height - by) * scale
);
textureElements.push(
posX, posY,
posX + width, posY,
posX, posY + height,
posX + width, posY,
posX, posY + height,
posX + width, posY + height
);
pen.x = pen.x + advance * scale;
}
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexElements), gl.STATIC_DRAW);
vertexBuffer.numItems = vertexElements.length / 2;
gl.bindBuffer(gl.ARRAY_BUFFER, textureBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureElements), gl.STATIC_DRAW);
textureBuffer.numItems = textureElements.length / 2;
}
function drawGL() {
gl.clearColor(0.8, 0.8, 0.8, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const scale = +document.getElementById('scale').value * window.devicePixelRatio / 2;
const buffer = +document.getElementById('halo').value;
const angle = +document.getElementById('angle').value;
const gamma = +document.getElementById('gamma').value;
drawText(scale);
const mvMatrix = mat4.create();
mat4.translate(mvMatrix, mvMatrix, [canvas2.width / 2, canvas2.height / 2, 0]);
mat4.rotateZ(mvMatrix, mvMatrix, angle);
mat4.translate(mvMatrix, mvMatrix, [-canvas2.width / 2, -canvas2.height / 2, 0]);
const mvpMatrix = mat4.create();
mat4.multiply(mvpMatrix, pMatrix, mvMatrix);
gl.uniformMatrix4fv(shader.u_matrix, false, mvpMatrix);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.uniform1i(shader.u_texture, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.vertexAttribPointer(shader.a_pos, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, textureBuffer);
gl.vertexAttribPointer(shader.a_texcoord, 2, gl.FLOAT, false, 0, 0);
gl.uniform4fv(shader.u_color, [1, 1, 1, 1]);
gl.uniform1f(shader.u_buffer, buffer);
gl.drawArrays(gl.TRIANGLES, 0, vertexBuffer.numItems);
gl.uniform4fv(shader.u_color, [0, 0, 0, 1]);
gl.uniform1f(shader.u_buffer, 0.75);
gl.uniform1f(shader.u_gamma, gamma * 1.4142 / scale);
gl.drawArrays(gl.TRIANGLES, 0, vertexBuffer.numItems);
}
document.getElementById('fontsize').oninput = frame;
document.getElementById('fontweight').oninput = frame;
document.getElementById('scale').oninput = drawGL;
document.getElementById('halo').oninput = drawGL;
document.getElementById('angle').oninput = drawGL;
document.getElementById('gamma').oninput = drawGL;
let frameId;
function frame() {
cancelAnimationFrame(frameId);
frameId = requestAnimationFrame(update);
}
function update() {
updateSDF();
const sdfData = new Uint8Array(ctx.getImageData(0, 0, canvas.width, canvas.height).data);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, sdfData);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.uniform2f(shader.u_texsize, canvas.width, canvas.height);
drawGL();
}
update();
function createShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(gl.getShaderInfoLog(shader));
}
return shader;
}
function createProgram(gl, vertexSource, fragmentSource) {
const program = gl.createProgram();
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentSource);
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error(gl.getProgramInfoLog(program));
}
const wrapper = {program};
const numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
for (let i = 0; i < numAttributes; i++) {
const attribute = gl.getActiveAttrib(program, i);
wrapper[attribute.name] = gl.getAttribLocation(program, attribute.name);
}
const numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
for (let i = 0; i < numUniforms; i++) {
const uniform = gl.getActiveUniform(program, i);
wrapper[uniform.name] = gl.getUniformLocation(program, uniform.name);
}
return wrapper;
}
</script>
</body>
</html>