Rendering Text in a WebGL Map

In the last couple of articles, I covered building a vector map from scratch using WebGL, and then selecting objects on it. But there's still something pretty obvious missing from the map: none of it is labeled.

Text is a bit trickier than polygons, since WebGL doesn't have a built-in way to draw it. All it really knows how to draw is triangles.

In this article, I'll walk through rendering labels using a font atlas, and then improve on it using signed distance fields (SDF), which is the technique that libraries like Mapbox GL JS use for their text.

labels rendered in webgl, using a signed distance field for each character.

labels rendered in webgl, using a signed distance field for each character.

TL;DR - You can also skip straight to the final result.

Why not use the DOM

We've actually been putting text on the map since the first article. The tile coordinates in the corner of each tile (and the popup from the last article) are just DOM elements, positioned on top of the canvas.

That's fine for a handful of elements, but a map can easily have hundreds of labels in view, and every one of them would need to be moved on each frame. So ideally, the text gets drawn in WebGL along with everything else.

Getting the labels

The first thing we need is something to label. Along with the layers we've been rendering, the tiles also have a place layer, which has the names of cities, towns and neighborhoods.

Unlike the other layers, these features are points instead of polygons, so there's nothing to convert into triangles. All we need from each one is the name, and where it goes.

// get the labels (text & position) from a layer of points const getLabels = (vectorTileLayer, x, y, z) => { const labels = []; for (let i = 0; i < vectorTileLayer.length; i++) { const feature = vectorTileLayer.feature(i); const text = feature.properties['name:latin'] || feature.properties.name; const geojson = feature.toGeoJSON(x, y, z); if (!text || geojson.geometry.type !== 'Point') { continue; // only points with a name } // tiles also include points from outside of their bounds, // skip those so the label doesn't get drawn by multiple tiles const [[point]] = feature.loadGeometry(); const { extent } = vectorTileLayer; if (point.x < 0 || point.x >= extent || point.y < 0 || point.y >= extent) { continue; } labels.push({ text, position: MercatorCoordinate.fromLngLat(geojson.geometry.coordinates), }); } return labels; };

One thing to note is the tiles also include points from outside of their own bounds (quite a lot of them). Since we're rendering every tile in view, those labels would end up getting drawn more than once, so we'll skip anything that isn't inside of the tile.

Creating a font atlas

WebGL can't draw text, but it can draw images (or textures). So the idea is to draw all of the characters we need into a single image ahead of time, and then copy each one out of it as it's needed. This is generally referred to as a font atlas.

Fortunately, the browser already knows how to draw text into an image. We can create a regular 2D canvas, and use fillText to draw each character (or glyph) into its own cell.

// draw a character into the atlas (white on black) const drawBitmapGlyph = (ctx, char, x, y) => { ctx.font = `${FONT_WEIGHT} ${FONT_SIZE}px ${FONT_FAMILY}`; ctx.textBaseline = 'alphabetic'; ctx.fillStyle = 'white'; ctx.fillText(char, x + PADDING, y + BASELINE); const { width } = ctx.measureText(char); return { x, y, width: CELL_SIZE, height: CELL_SIZE, left: -PADDING, // left edge of the cell, relative to the start of the character top: BASELINE, // top edge of the cell, relative to the baseline advance: width, // how far to move over for the next character }; };

Along with drawing the glyph, we're keeping track of where it is in the atlas, and how far to move over before drawing the next character (known as the advance).

the font atlas, with a cell for each character.

the font atlas, with a cell for each character.

The atlas starts out with the basic characters. Anything else (like an accented character) gets added to the next open cell the first time a label needs it.

Building the text

Now that we have the glyphs, we need some geometry to draw them on. Each character in a label becomes a rectangle (or quad) made up of two triangles, just like the bounding box from the first article.

each character is a quad, which gets its pixels from a cell in the atlas.

each character is a quad, which gets its pixels from a cell in the atlas.

Every vertex in a quad needs three pieces of information:

  • anchor: the position of the label on the map (the same for every vertex in the label)
  • offset: where the vertex is relative to the anchor, in pixels
  • texcoord: where the vertex is in the atlas
// start half of the width to the left, so the text ends up centered const width = glyphs.reduce((total, glyph) => total + glyph.advance, 0); let x = -width / 2; const baseline = FONT_SIZE * 0.35; // roughly half the height of a capital letter glyphs.forEach((glyph) => { // corners of the quad const x0 = x + glyph.left; const y0 = baseline - glyph.top; const x1 = x0 + glyph.width; const y1 = y0 + glyph.height; // same corners in the atlas const u0 = glyph.x / ATLAS_SIZE; const v0 = glyph.y / ATLAS_SIZE; const u1 = (glyph.x + glyph.width) / ATLAS_SIZE; const v1 = (glyph.y + glyph.height) / ATLAS_SIZE; // 2 triangles offsets.push(x0, y0, x1, y0, x0, y1, x0, y1, x1, y0, x1, y1); texcoords.push(u0, v0, u1, v0, u0, v1, u0, v1, u1, v0, u1, v1); for (let i = 0; i < 6; i++) { anchors.push(anchor[0], anchor[1]); // same for every vertex } x += glyph.advance; // move over for the next character });

The reason for splitting the position into an anchor & an offset is that text behaves differently than the rest of the map. The polygons get bigger as we zoom in, but the text should stay the same size.

So in the vertex shader, only the anchor gets moved by the matrix. The offset gets added on afterwards, once it's been converted from pixels to clip space.

attribute vec2 a_anchor; // position of the label on the map attribute vec2 a_offset; // position of the vertex relative to the anchor (in pixels) attribute vec2 a_texcoord; // position of the vertex in the atlas uniform mat3 u_matrix; // 3 X 3 matrix uniform vec2 u_resolution; // size of the canvas (in pixels) uniform float u_scale; // text size relative to the size in the atlas varying vec2 v_texcoord; void main() { v_texcoord = a_texcoord; vec2 anchor = (u_matrix * vec3(a_anchor, 1)).xy; // convert the offset from pixels to clip space (and flip the y) vec2 offset = a_offset * u_scale / u_resolution * vec2(2, -2); gl_Position = vec4(anchor + offset, 0, 1); }

The fragment shader uses texture2D to look up the pixel from the atlas. Since the atlas is white on black, that value tells us how much of the text color to use.

The last step is getting the atlas into WebGL. A canvas can be loaded directly into a texture, which we'll do again any time a new glyph gets added.

// create a texture for the font atlas const atlasTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, atlasTexture); 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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // reload the atlas if any glyphs have been added if (atlas.dirty) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, atlas.canvas); atlas.dirty = false; } // blend the text with what's already been drawn gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);

We also need to turn on blending when drawing the text. Most of each quad is empty, and without it those empty pixels would replace what's already been drawn underneath.

Putting it all together, we should now have some labels on the map. There's also a slider in the corner for changing the size of the text.

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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 import { mat3, vec3 } from 'gl-matrix'; import tilebelt from '@mapbox/tilebelt'; import MercatorCoordinate from './mercator-coordinate'; import Stats from 'stats.js'; import { createShader, createProgram } from './webgl-utils'; import { createBitmapAtlas, getTextVertices, FONT_SIZE } from './text-atlas'; import config from '../config'; ////////////////////// // constants ////////////////////// const TILE_SERVER_URL = `https://maps.ckochis.com/data/v3/{z}/{x}/{y}.pbf?apiKey=${config('mapsApiKey')}`; const TILE_SIZE = 512; const MAX_TILE_ZOOM = 14; const MIN_ZOOM = 0; const MAX_ZOOM = 16; const TEXT_COLOR = [51, 51, 51, 255]; const MIN_TEXT_SIZE = 12; const MAX_TEXT_SIZE = 64; ////////////////////// // shaders ////////////////////// // vertex shader just passes through the position, // no modification to the vertices const vertexShaderSource = ` attribute vec2 a_position; uniform mat3 u_matrix; // 3 X 3 matrix void main() { vec2 position = (u_matrix * vec3(a_position, 1)).xy; gl_Position = vec4(position, 0, 1); } `; // set color via uniform const fragmentShaderSource =` precision mediump float; uniform vec4 u_color; void main() { gl_FragColor = u_color; } `; // text vertex shader moves the anchor with the map, // then offsets each corner of the glyph by a fixed number of pixels const textVertexShaderSource = ` attribute vec2 a_anchor; // position of the label on the map attribute vec2 a_offset; // position of the vertex relative to the anchor (in pixels) attribute vec2 a_texcoord; // position of the vertex in the atlas uniform mat3 u_matrix; // 3 X 3 matrix uniform vec2 u_resolution; // size of the canvas (in pixels) uniform float u_scale; // text size relative to the size in the atlas varying vec2 v_texcoord; void main() { v_texcoord = a_texcoord; vec2 anchor = (u_matrix * vec3(a_anchor, 1)).xy; // convert the offset from pixels to clip space (and flip the y) vec2 offset = a_offset * u_scale / u_resolution * vec2(2, -2); gl_Position = vec4(anchor + offset, 0, 1); } `; // text fragment shader looks up the glyph from the atlas, // and uses it for how much of the text color to apply const textFragmentShaderSource = ` precision mediump float; uniform sampler2D u_atlas; uniform vec4 u_color; varying vec2 v_texcoord; void main() { // atlas is white on black, so any channel works float alpha = texture2D(u_atlas, v_texcoord).r; gl_FragColor = u_color * alpha; } `; ////////////////////// // map state ////////////////////// let loopRunning = true; let frame; // id of the next animation frame const camera = { x: 0, y: 0, zoom: 0, }; // initial transformation (New York) [camera.x, camera.y] = MercatorCoordinate.fromLngLat([-73.98, 40.72]); camera.zoom = 10.5; // DOM elements let canvas; let controls; let statsWidget; const LAYERS = { water: [180, 240, 250, 255], landcover: [202, 246, 193, 255], park: [202, 255, 193, 255], building: [185, 175, 139, 191], }; // layers to get labels from const LABEL_LAYERS = ['place']; const TILE_BUFFER = 1; // 1 tile in each direction let tiles = {}; // tile -> layers let tilesInView = []; let tileWorker; ////////////////////// // text state ////////////////////// let gl; let atlas; let atlasTexture; let textSize = 16; // in pixels function updateTiles() { const bbox = getBounds(); const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM); const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z); const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z); // tiles visible in viewport tilesInView = []; const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]]; const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]]; for (let x = minX; x <= maxX; x++) { for (let y = minY; y <= maxY; y++) { tilesInView.push([x, y, z]); } } // load additional tiles outside of viewport let bufferedTiles = []; for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) { for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) { bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction // load parent tiles 2 levels up bufferedTiles.push(tilebelt.getParent([bufX, bufY, z])); bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z]))); } } // remove dupes from in view let tilesToLoad = [ ...new Set([ ...tilesInView.map(t => t.join('/')), ...bufferedTiles.map(t => t.join('/')) ]) ]; // make sure tiles are in range tilesToLoad = tilesToLoad.filter((tile) => { const [x, y, z] = tile.split('/').map(Number); const N = Math.pow(2, z); const validX = x >= 0 && x < N; const validY = y >= 0 && y < N; const validZ = z >= 0 && z <= MAX_TILE_ZOOM; return validX && validY && validZ; }); tilesToLoad.forEach((tile) => { if (tiles[tile]) { return; // already loaded, no need to fetch } tiles[tile] = []; // temp hold for request // load tiles in worker tileWorker.postMessage({ tile, layers: LAYERS, labelLayers: LABEL_LAYERS, url: TILE_SERVER_URL }); }); } let matrix; function updateMatrix() { const cameraMat = mat3.create(); // translate mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]); // scale const zoomScale = 1 / Math.pow(2, camera.zoom); const widthScale = TILE_SIZE / canvas.width; const heightScale = TILE_SIZE / canvas.height; mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]); // update matrix matrix = mat3.multiply( [], mat3.create(), // identity matrix mat3.invert([], cameraMat) // invert camera position ); } // build the text vertices for all of the labels in a tile layer function createTextVertices(labels) { const anchors = []; const offsets = []; const texcoords = []; labels.forEach(({ text, position }) => { const vertices = getTextVertices(atlas, text, position); anchors.push(...vertices.anchors); offsets.push(...vertices.offsets); texcoords.push(...vertices.texcoords); }); return { anchors: Float32Array.from(anchors), offsets: Float32Array.from(offsets), texcoords: Float32Array.from(texcoords), }; } ////////////////////// // helpers ////////////////////// function getClipSpacePosition(e) { // handle mouse and touch events const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left; const cssY = y - rect.top; // get normalized 0 to 1 position across and down canvas const normalizedX = cssX / canvas.clientWidth; const normalizedY = cssY / canvas.clientHeight; // convert to clip space const clipX = normalizedX * 2 - 1; const clipY = normalizedY * -2 + 1; return [clipX, clipY]; } // get bbox coordinates for viewport function getBounds() { const zoomScale = Math.pow(2, camera.zoom); // undo clip-space const px = (1 + camera.x) / 2; const py = (1 - camera.y) / 2; // get world coord in px const wx = px * TILE_SIZE; const wy = py * TILE_SIZE; // get zoom px const zx = wx * zoomScale; const zy = wy * zoomScale; // get bottom-left and top-right pixels let x1 = zx - (canvas.width / 2); let y1 = zy + (canvas.height / 2); let x2 = zx + (canvas.width / 2); let y2 = zy - (canvas.height / 2); // convert to world coords x1 = x1 / zoomScale / TILE_SIZE; y1 = y1 / zoomScale / TILE_SIZE; x2 = x2 / zoomScale / TILE_SIZE; y2 = y2 / zoomScale / TILE_SIZE; // get LngLat bounding box const bbox = [ Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180), Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05), Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180), Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05), ]; return bbox; } function atLimits() { const bbox = getBounds(); return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05; } ////////////////////// // main program ////////////////////// let hammer; let handlePan; let handleZoom; let timestamp; let slowCount; const run = (canvasId, abort) => { // setup loop state loopRunning = true; timestamp = 0; slowCount = 0; // create stats object for widget const stats = new Stats(); // get GL context from canvas canvas = document.getElementById(canvasId); gl = canvas.getContext("webgl"); // create the font atlas // (only once, glyphs are added to it as the labels get loaded) if (!atlas) { atlas = createBitmapAtlas(); } atlas.dirty = true; // needs to be loaded into the texture // setup tile worker if (!tileWorker) { tileWorker = new Worker(new URL('./text-tile-worker.js', import.meta.url)); tileWorker.onmessage = (event) => { const { tile, tileData } = event.data; // convert the labels in the tile to text vertices (tileData || []).forEach((tileLayer) => { if (tileLayer.labels) { tileLayer.text = createTextVertices(tileLayer.labels); } }); tiles[tile] = tileData; }; tileWorker.onerror = (error) => { console.error('Uncaught worker error.', error); }; } // setup initial state updateMatrix(); updateTiles(); // setup viewport gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); gl.clearColor(0, 0, 0, 0); // init gl program for the map layers const program = createProgram( gl, createShader(gl, gl.VERTEX_SHADER, vertexShaderSource), createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource), ); const positionAttributeLocation = gl.getAttribLocation(program, "a_position"); const matrixLocation = gl.getUniformLocation(program, "u_matrix"); const colorLocation = gl.getUniformLocation(program, "u_color"); // init gl program for the text const textProgram = createProgram( gl, createShader(gl, gl.VERTEX_SHADER, textVertexShaderSource), createShader(gl, gl.FRAGMENT_SHADER, textFragmentShaderSource), ); const anchorAttributeLocation = gl.getAttribLocation(textProgram, "a_anchor"); const offsetAttributeLocation = gl.getAttribLocation(textProgram, "a_offset"); const texcoordAttributeLocation = gl.getAttribLocation(textProgram, "a_texcoord"); const textMatrixLocation = gl.getUniformLocation(textProgram, "u_matrix"); const resolutionLocation = gl.getUniformLocation(textProgram, "u_resolution"); const scaleLocation = gl.getUniformLocation(textProgram, "u_scale"); const atlasLocation = gl.getUniformLocation(textProgram, "u_atlas"); const textColorLocation = gl.getUniformLocation(textProgram, "u_color"); // create buffers const positionBuffer = gl.createBuffer(); const anchorBuffer = gl.createBuffer(); const offsetBuffer = gl.createBuffer(); const texcoordBuffer = gl.createBuffer(); // create a texture for the font atlas atlasTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, atlasTexture); 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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // load data into a buffer, and tell the attribute how to get data out of it // (every attribute is 2 floats per vertex) const setAttribute = (location, buffer, data) => { gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); gl.enableVertexAttribArray(location); const size = 2; const type = gl.FLOAT; const normalize = false; const stride = 0; const offset = 0; gl.vertexAttribPointer(location, size, type, normalize, stride, offset); }; // render the map layers for the tiles in view const drawTiles = () => { gl.useProgram(program); // set matrix as uniform gl.uniformMatrix3fv(matrixLocation, false, matrix); tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { layer, vertices } = tileLayer; if (LAYERS[layer] && vertices) { const color = LAYERS[layer].map(n => n / 255); // set color uniform for layer gl.uniform4fv(colorLocation, color); // load vertices for layer setAttribute(positionAttributeLocation, positionBuffer, vertices); // draw const primitiveType = gl.TRIANGLES; const offset = 0; const count = vertices.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // render the labels for the tiles in view const drawLabels = () => { tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { text } = tileLayer; if (text && text.anchors.length > 0) { // load vertices for labels setAttribute(anchorAttributeLocation, anchorBuffer, text.anchors); setAttribute(offsetAttributeLocation, offsetBuffer, text.offsets); setAttribute(texcoordAttributeLocation, texcoordBuffer, text.texcoords); // draw const primitiveType = gl.TRIANGLES; const offset = 0; const count = text.anchors.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // render the text on top of the map const drawText = () => { gl.useProgram(textProgram); // reload the atlas if any glyphs have been added gl.bindTexture(gl.TEXTURE_2D, atlasTexture); if (atlas.dirty) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, atlas.canvas); atlas.dirty = false; } // blend the text with what's already been drawn gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // set uniforms const scale = textSize / FONT_SIZE; gl.uniformMatrix3fv(textMatrixLocation, false, matrix); gl.uniform2f(resolutionLocation, canvas.width, canvas.height); gl.uniform1f(scaleLocation, scale); gl.uniform1i(atlasLocation, 0); // texture unit 0 gl.uniform4fv(textColorLocation, TEXT_COLOR.map(n => n / 255)); drawLabels(); // reset for the map layers gl.disable(gl.BLEND); gl.disableVertexAttribArray(anchorAttributeLocation); gl.disableVertexAttribArray(offsetAttributeLocation); gl.disableVertexAttribArray(texcoordAttributeLocation); }; const draw = () => { stats.begin(); drawTiles(); drawText(); // kill loop if gets too slow // 10 frames under 10 FPS const now = performance.now(); const fps = 1 / ((now - timestamp) / 1000); if (fps < 10) { slowCount++; if (slowCount > 10) { console.warn(`Too slow. Killing loop for ${canvasId}.`); stop(); if (abort) { abort(); } } } timestamp = now; // end of loop stats.end(); if (loopRunning) { frame = window.requestAnimationFrame(draw); } } frame = window.requestAnimationFrame(draw); // start loop //////////////////////// // interaction handlers //////////////////////// // handle touch events const Hammer = require('hammerjs'); hammer = new Hammer(canvas); hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL }); hammer.get('pinch').set({ enable: true }); // handle pan events let startX; let startY; // handle drag changes while mouse is still down const handleMove = (moveEvent) => { const [x, y] = getClipSpacePosition(moveEvent); // compute the previous position in world space const [preX, preY] = vec3.transformMat3( [], [startX, startY, 0], mat3.invert([], matrix) ); // compute the new position in world space const [postX, postY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // move that amount, because how much the position changes depends on the zoom level const deltaX = preX - postX; const deltaY = preY - postY; if (isNaN(deltaX) || isNaN(deltaY)) { return; // abort } // only update within world limits camera.x += deltaX; camera.y += deltaY; // update matrix with new camera updateMatrix(); // prevent further pan if at limits if (atLimits()) { camera.x -= deltaX; camera.y -= deltaY; updateMatrix(); return; // abort } // save current pos for next movement startX = x; startY = y; updateMatrix(); updateTiles(); } handlePan = (startEvent) => { // get position of initial drag [startX, startY] = getClipSpacePosition(startEvent); canvas.style.cursor = 'grabbing'; window.addEventListener('mousemove', handleMove); hammer.on('pan', handleMove); // clear on release const clear = (event) => { canvas.style.cursor = 'grab'; window.removeEventListener('mousemove', handleMove); window.removeEventListener('mouseup', clear); hammer.off('pan', handleMove); hammer.off('panend', clear); }; window.addEventListener('mouseup', clear); hammer.on('panend', clear); } canvas.addEventListener('mousedown', handlePan); hammer.on('panstart', handlePan); // handle zoom events handleZoom = (wheelEvent) => { wheelEvent.preventDefault(); const [x, y] = getClipSpacePosition(wheelEvent); // get position before zooming const [preZoomX, preZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // update current zoom state const prevZoom = camera.zoom; const zoomDelta = -wheelEvent.deltaY * (1 / 500); camera.zoom += zoomDelta; camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM)); updateMatrix(); // prevent further zoom if at limits if (atLimits()) { camera.zoom = prevZoom updateMatrix(); return; } // get new position after zooming const [postZoomX, postZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // camera needs to be translated the difference of before and after camera.x += preZoomX - postZoomX; camera.y += preZoomY - postZoomY; updateMatrix(); updateTiles(); } canvas.addEventListener('wheel', handleZoom); hammer.on('pinch', handleZoom); // setup slider for the text size controls = document.createElement('label'); controls.className = 'webgl-map-controls'; const sizeLabel = document.createElement('span'); sizeLabel.textContent = `text size: ${textSize}px`; const slider = document.createElement('input'); slider.type = 'range'; slider.min = MIN_TEXT_SIZE; slider.max = MAX_TEXT_SIZE; slider.value = textSize; slider.addEventListener('input', () => { textSize = Number(slider.value); sizeLabel.textContent = `text size: ${textSize}px`; }); controls.append(sizeLabel, slider); canvas.parentElement.appendChild(controls); // setup stats widget stats.showPanel(0); // frame rate statsWidget = stats.dom; statsWidget.style.position = 'absolute'; statsWidget.style.zIndex = '0'; canvas.parentElement.appendChild(statsWidget); }; export const stop = () => { loopRunning = false; window.cancelAnimationFrame(frame); if (!canvas) { return; // not running, nothing to clean up } // clear event handlers canvas.removeEventListener('wheel', handleZoom); canvas.removeEventListener('mousedown', handlePan); hammer.destroy(); // clear DOM elements statsWidget.remove(); controls.remove(); // clear atlas texture gl.deleteTexture(atlasTexture); canvas = null; }; export default run;

Scaling the text

At the default size, the text looks pretty good. But if you drag the slider to make it bigger, it starts to get blurry.

That's because the glyphs in the atlas were drawn at 24px. To draw them any bigger, the GPU has to stretch the image, and it fills in the missing pixels by blending the ones next to them. It's the same thing that happens when you zoom in on a photo.

a glyph from the atlas, and what it looks like scaled up.

a glyph from the atlas, and what it looks like scaled up.

We could draw the glyphs at a bigger size, but that just moves the problem (and uses more memory). A map will usually have labels at a bunch of different sizes, and ideally one atlas could handle all of them.

Signed distance fields

This is where signed distance fields come in. The name makes it sound more complicated than it is.

In the atlas we have now, each pixel answers the question "is this pixel inside the letter?" (white for yes, black for no). In a distance field, each pixel answers a different question: "how far is this pixel from the edge of the letter?"

A pixel right on the edge gets a value of 0.5 (gray). The further inside the letter it is, the brighter it gets, and the further outside, the darker. That's where the "signed" part comes from, since inside & outside are on opposite sides of the edge.

the same glyph as a distance field. the red line is where the value crosses 0.5.

the same glyph as a distance field. the red line is where the value crosses 0.5.

On its own, this just looks like a blurry version of the letter. The difference is in what happens when it gets scaled up.

Blending a white pixel with a black one gives us gray, and all that really tells us is the edge is somewhere nearby. But blending two distances gives us another distance. For instance, halfway between a pixel that's 2 pixels inside the letter, and one that's 2 pixels outside, is right on the edge.

So no matter how far the texture gets stretched, we can still work out where the edge of the letter is. It's wherever the value crosses 0.5. All the fragment shader needs to do is fill in the pixels that are above 0.5, and leave out the ones below.

It's not perfect. At 12x the curves start to get a bit lumpy, since there's only so much detail in a 24px glyph. But the edge stays sharp, which is a big improvement over the blur.

I won't go into too much detail on the theory here, but the technique was popularized by a paper from Valve if you're interested in reading more.

Generating the distances

Working out the distance for every pixel is a bit more involved than drawing the letter, so I'm not going to do that part from scratch. Fortunately, Mapbox has a small library called TinySDF that does just that. It draws the character to a canvas the same way we were, and then calculates the distances from it.

const tinySdf = new TinySDF({ fontSize: FONT_SIZE, fontFamily: FONT_FAMILY, fontWeight: FONT_WEIGHT, buffer: SDF_BUFFER, radius: SDF_RADIUS, cutoff: 0.5, // edge of the glyph is at 0.5 }); // draw the distance field for a character into the atlas const drawSDFGlyph = (ctx, char, x, y) => { // data has a single value (0 - 255) for each pixel const glyph = tinySdf.draw(char); const width = Math.min(glyph.width, CELL_SIZE); const height = Math.min(glyph.height, CELL_SIZE); // copy the distances into the atlas as shades of gray const image = ctx.createImageData(width, height); for (let row = 0; row < height; row++) { for (let col = 0; col < width; col++) { const distance = glyph.data[row * glyph.width + col]; image.data.set([distance, distance, distance, 255], (row * width + col) * 4); } } ctx.putImageData(image, x, y); return { x, y, width, height, left: glyph.glyphLeft - SDF_BUFFER, // left edge of the cell, relative to the start of the character top: glyph.glyphTop + SDF_BUFFER, // top edge of the cell, relative to the baseline advance: glyph.glyphAdvance, // how far to move over for the next character }; };

There are a few settings worth mentioning. The buffer adds some empty space around each glyph, since the distances extend past the edge of the letter. The radius is how many pixels of distance get spread across the 0 to 1 range, and a cutoff of 0.5 puts the edge right in the middle of it.

the same atlas, with a distance field for each character.

the same atlas, with a distance field for each character.

The nice part is that nothing else about the atlas changes. The glyphs are still in cells, and the quads get built exactly the same way. The only other thing we need to update is the fragment shader.

Updating the shader

Instead of using the value from the atlas directly, we now check it against the edge at 0.5. A hard cutoff would leave us with jagged edges though, so we'll use smoothstep to fade from 0 to 1 over a small range on either side of it.

precision mediump float; uniform sampler2D u_atlas; uniform vec4 u_color; uniform float u_smoothing; // how much to smooth the edge varying vec2 v_texcoord; void main() { // edge of the glyph is at 0.5 float dist = texture2D(u_atlas, v_texcoord).r; float alpha = smoothstep(0.5 - u_smoothing, 0.5 + u_smoothing, dist); gl_FragColor = u_color * alpha; }

How small that range is depends on the size of the text. Ideally the fade is about a pixel wide on the screen, so we can work that out from the scale, and pass it in as a uniform.

const scale = textSize / FONT_SIZE; // the distance changes by (1 / SDF_RADIUS) for each pixel in the atlas, // so this is how much it changes for each pixel on the screen const pixel = 1 / (SDF_RADIUS * scale); gl.uniform1f(smoothingLocation, 0.7 * pixel); // smooth the edge over about a pixel
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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 import { mat3, vec3 } from 'gl-matrix'; import tilebelt from '@mapbox/tilebelt'; import MercatorCoordinate from './mercator-coordinate'; import Stats from 'stats.js'; import { createShader, createProgram } from './webgl-utils'; import { createSDFAtlas, getTextVertices, FONT_SIZE, SDF_RADIUS } from './text-atlas'; import config from '../config'; ////////////////////// // constants ////////////////////// const TILE_SERVER_URL = `https://maps.ckochis.com/data/v3/{z}/{x}/{y}.pbf?apiKey=${config('mapsApiKey')}`; const TILE_SIZE = 512; const MAX_TILE_ZOOM = 14; const MIN_ZOOM = 0; const MAX_ZOOM = 16; const TEXT_COLOR = [51, 51, 51, 255]; const MIN_TEXT_SIZE = 12; const MAX_TEXT_SIZE = 64; ////////////////////// // shaders ////////////////////// // vertex shader just passes through the position, // no modification to the vertices const vertexShaderSource = ` attribute vec2 a_position; uniform mat3 u_matrix; // 3 X 3 matrix void main() { vec2 position = (u_matrix * vec3(a_position, 1)).xy; gl_Position = vec4(position, 0, 1); } `; // set color via uniform const fragmentShaderSource =` precision mediump float; uniform vec4 u_color; void main() { gl_FragColor = u_color; } `; // text vertex shader moves the anchor with the map, // then offsets each corner of the glyph by a fixed number of pixels const textVertexShaderSource = ` attribute vec2 a_anchor; // position of the label on the map attribute vec2 a_offset; // position of the vertex relative to the anchor (in pixels) attribute vec2 a_texcoord; // position of the vertex in the atlas uniform mat3 u_matrix; // 3 X 3 matrix uniform vec2 u_resolution; // size of the canvas (in pixels) uniform float u_scale; // text size relative to the size in the atlas varying vec2 v_texcoord; void main() { v_texcoord = a_texcoord; vec2 anchor = (u_matrix * vec3(a_anchor, 1)).xy; // convert the offset from pixels to clip space (and flip the y) vec2 offset = a_offset * u_scale / u_resolution * vec2(2, -2); gl_Position = vec4(anchor + offset, 0, 1); } `; // text fragment shader looks up the distance from the atlas, // and fills in the pixel if it's on the inside of the edge const textFragmentShaderSource = ` precision mediump float; uniform sampler2D u_atlas; uniform vec4 u_color; uniform float u_smoothing; // how much to smooth the edge varying vec2 v_texcoord; void main() { // edge of the glyph is at 0.5 float dist = texture2D(u_atlas, v_texcoord).r; float alpha = smoothstep(0.5 - u_smoothing, 0.5 + u_smoothing, dist); gl_FragColor = u_color * alpha; } `; ////////////////////// // map state ////////////////////// let loopRunning = true; let frame; // id of the next animation frame const camera = { x: 0, y: 0, zoom: 0, }; // initial transformation (New York) [camera.x, camera.y] = MercatorCoordinate.fromLngLat([-73.98, 40.72]); camera.zoom = 10.5; // DOM elements let canvas; let controls; let statsWidget; const LAYERS = { water: [180, 240, 250, 255], landcover: [202, 246, 193, 255], park: [202, 255, 193, 255], building: [185, 175, 139, 191], }; // layers to get labels from const LABEL_LAYERS = ['place']; const TILE_BUFFER = 1; // 1 tile in each direction let tiles = {}; // tile -> layers let tilesInView = []; let tileWorker; ////////////////////// // text state ////////////////////// let gl; let atlas; let atlasTexture; let textSize = 16; // in pixels function updateTiles() { const bbox = getBounds(); const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM); const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z); const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z); // tiles visible in viewport tilesInView = []; const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]]; const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]]; for (let x = minX; x <= maxX; x++) { for (let y = minY; y <= maxY; y++) { tilesInView.push([x, y, z]); } } // load additional tiles outside of viewport let bufferedTiles = []; for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) { for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) { bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction // load parent tiles 2 levels up bufferedTiles.push(tilebelt.getParent([bufX, bufY, z])); bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z]))); } } // remove dupes from in view let tilesToLoad = [ ...new Set([ ...tilesInView.map(t => t.join('/')), ...bufferedTiles.map(t => t.join('/')) ]) ]; // make sure tiles are in range tilesToLoad = tilesToLoad.filter((tile) => { const [x, y, z] = tile.split('/').map(Number); const N = Math.pow(2, z); const validX = x >= 0 && x < N; const validY = y >= 0 && y < N; const validZ = z >= 0 && z <= MAX_TILE_ZOOM; return validX && validY && validZ; }); tilesToLoad.forEach((tile) => { if (tiles[tile]) { return; // already loaded, no need to fetch } tiles[tile] = []; // temp hold for request // load tiles in worker tileWorker.postMessage({ tile, layers: LAYERS, labelLayers: LABEL_LAYERS, url: TILE_SERVER_URL }); }); } let matrix; function updateMatrix() { const cameraMat = mat3.create(); // translate mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]); // scale const zoomScale = 1 / Math.pow(2, camera.zoom); const widthScale = TILE_SIZE / canvas.width; const heightScale = TILE_SIZE / canvas.height; mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]); // update matrix matrix = mat3.multiply( [], mat3.create(), // identity matrix mat3.invert([], cameraMat) // invert camera position ); } // build the text vertices for all of the labels in a tile layer function createTextVertices(labels) { const anchors = []; const offsets = []; const texcoords = []; labels.forEach(({ text, position }) => { const vertices = getTextVertices(atlas, text, position); anchors.push(...vertices.anchors); offsets.push(...vertices.offsets); texcoords.push(...vertices.texcoords); }); return { anchors: Float32Array.from(anchors), offsets: Float32Array.from(offsets), texcoords: Float32Array.from(texcoords), }; } ////////////////////// // helpers ////////////////////// function getClipSpacePosition(e) { // handle mouse and touch events const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left; const cssY = y - rect.top; // get normalized 0 to 1 position across and down canvas const normalizedX = cssX / canvas.clientWidth; const normalizedY = cssY / canvas.clientHeight; // convert to clip space const clipX = normalizedX * 2 - 1; const clipY = normalizedY * -2 + 1; return [clipX, clipY]; } // get bbox coordinates for viewport function getBounds() { const zoomScale = Math.pow(2, camera.zoom); // undo clip-space const px = (1 + camera.x) / 2; const py = (1 - camera.y) / 2; // get world coord in px const wx = px * TILE_SIZE; const wy = py * TILE_SIZE; // get zoom px const zx = wx * zoomScale; const zy = wy * zoomScale; // get bottom-left and top-right pixels let x1 = zx - (canvas.width / 2); let y1 = zy + (canvas.height / 2); let x2 = zx + (canvas.width / 2); let y2 = zy - (canvas.height / 2); // convert to world coords x1 = x1 / zoomScale / TILE_SIZE; y1 = y1 / zoomScale / TILE_SIZE; x2 = x2 / zoomScale / TILE_SIZE; y2 = y2 / zoomScale / TILE_SIZE; // get LngLat bounding box const bbox = [ Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180), Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05), Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180), Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05), ]; return bbox; } function atLimits() { const bbox = getBounds(); return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05; } ////////////////////// // main program ////////////////////// let hammer; let handlePan; let handleZoom; let timestamp; let slowCount; const run = (canvasId, abort) => { // setup loop state loopRunning = true; timestamp = 0; slowCount = 0; // create stats object for widget const stats = new Stats(); // get GL context from canvas canvas = document.getElementById(canvasId); gl = canvas.getContext("webgl"); // create the font atlas // (only once, glyphs are added to it as the labels get loaded) if (!atlas) { atlas = createSDFAtlas(); } atlas.dirty = true; // needs to be loaded into the texture // setup tile worker if (!tileWorker) { tileWorker = new Worker(new URL('./text-tile-worker.js', import.meta.url)); tileWorker.onmessage = (event) => { const { tile, tileData } = event.data; // convert the labels in the tile to text vertices (tileData || []).forEach((tileLayer) => { if (tileLayer.labels) { tileLayer.text = createTextVertices(tileLayer.labels); } }); tiles[tile] = tileData; }; tileWorker.onerror = (error) => { console.error('Uncaught worker error.', error); }; } // setup initial state updateMatrix(); updateTiles(); // setup viewport gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); gl.clearColor(0, 0, 0, 0); // init gl program for the map layers const program = createProgram( gl, createShader(gl, gl.VERTEX_SHADER, vertexShaderSource), createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource), ); const positionAttributeLocation = gl.getAttribLocation(program, "a_position"); const matrixLocation = gl.getUniformLocation(program, "u_matrix"); const colorLocation = gl.getUniformLocation(program, "u_color"); // init gl program for the text const textProgram = createProgram( gl, createShader(gl, gl.VERTEX_SHADER, textVertexShaderSource), createShader(gl, gl.FRAGMENT_SHADER, textFragmentShaderSource), ); const anchorAttributeLocation = gl.getAttribLocation(textProgram, "a_anchor"); const offsetAttributeLocation = gl.getAttribLocation(textProgram, "a_offset"); const texcoordAttributeLocation = gl.getAttribLocation(textProgram, "a_texcoord"); const textMatrixLocation = gl.getUniformLocation(textProgram, "u_matrix"); const resolutionLocation = gl.getUniformLocation(textProgram, "u_resolution"); const scaleLocation = gl.getUniformLocation(textProgram, "u_scale"); const atlasLocation = gl.getUniformLocation(textProgram, "u_atlas"); const textColorLocation = gl.getUniformLocation(textProgram, "u_color"); const smoothingLocation = gl.getUniformLocation(textProgram, "u_smoothing"); // create buffers const positionBuffer = gl.createBuffer(); const anchorBuffer = gl.createBuffer(); const offsetBuffer = gl.createBuffer(); const texcoordBuffer = gl.createBuffer(); // create a texture for the font atlas atlasTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, atlasTexture); 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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // load data into a buffer, and tell the attribute how to get data out of it // (every attribute is 2 floats per vertex) const setAttribute = (location, buffer, data) => { gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); gl.enableVertexAttribArray(location); const size = 2; const type = gl.FLOAT; const normalize = false; const stride = 0; const offset = 0; gl.vertexAttribPointer(location, size, type, normalize, stride, offset); }; // render the map layers for the tiles in view const drawTiles = () => { gl.useProgram(program); // set matrix as uniform gl.uniformMatrix3fv(matrixLocation, false, matrix); tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { layer, vertices } = tileLayer; if (LAYERS[layer] && vertices) { const color = LAYERS[layer].map(n => n / 255); // set color uniform for layer gl.uniform4fv(colorLocation, color); // load vertices for layer setAttribute(positionAttributeLocation, positionBuffer, vertices); // draw const primitiveType = gl.TRIANGLES; const offset = 0; const count = vertices.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // render the labels for the tiles in view const drawLabels = () => { tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { text } = tileLayer; if (text && text.anchors.length > 0) { // load vertices for labels setAttribute(anchorAttributeLocation, anchorBuffer, text.anchors); setAttribute(offsetAttributeLocation, offsetBuffer, text.offsets); setAttribute(texcoordAttributeLocation, texcoordBuffer, text.texcoords); // draw const primitiveType = gl.TRIANGLES; const offset = 0; const count = text.anchors.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // render the text on top of the map const drawText = () => { gl.useProgram(textProgram); // reload the atlas if any glyphs have been added gl.bindTexture(gl.TEXTURE_2D, atlasTexture); if (atlas.dirty) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, atlas.canvas); atlas.dirty = false; } // blend the text with what's already been drawn gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // set uniforms const scale = textSize / FONT_SIZE; gl.uniformMatrix3fv(textMatrixLocation, false, matrix); gl.uniform2f(resolutionLocation, canvas.width, canvas.height); gl.uniform1f(scaleLocation, scale); gl.uniform1i(atlasLocation, 0); // texture unit 0 gl.uniform4fv(textColorLocation, TEXT_COLOR.map(n => n / 255)); // the distance changes by (1 / SDF_RADIUS) for each pixel in the atlas, // so this is how much it changes for each pixel on the screen const pixel = 1 / (SDF_RADIUS * scale); gl.uniform1f(smoothingLocation, 0.7 * pixel); // smooth the edge over about a pixel drawLabels(); // reset for the map layers gl.disable(gl.BLEND); gl.disableVertexAttribArray(anchorAttributeLocation); gl.disableVertexAttribArray(offsetAttributeLocation); gl.disableVertexAttribArray(texcoordAttributeLocation); }; const draw = () => { stats.begin(); drawTiles(); drawText(); // kill loop if gets too slow // 10 frames under 10 FPS const now = performance.now(); const fps = 1 / ((now - timestamp) / 1000); if (fps < 10) { slowCount++; if (slowCount > 10) { console.warn(`Too slow. Killing loop for ${canvasId}.`); stop(); if (abort) { abort(); } } } timestamp = now; // end of loop stats.end(); if (loopRunning) { frame = window.requestAnimationFrame(draw); } } frame = window.requestAnimationFrame(draw); // start loop //////////////////////// // interaction handlers //////////////////////// // handle touch events const Hammer = require('hammerjs'); hammer = new Hammer(canvas); hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL }); hammer.get('pinch').set({ enable: true }); // handle pan events let startX; let startY; // handle drag changes while mouse is still down const handleMove = (moveEvent) => { const [x, y] = getClipSpacePosition(moveEvent); // compute the previous position in world space const [preX, preY] = vec3.transformMat3( [], [startX, startY, 0], mat3.invert([], matrix) ); // compute the new position in world space const [postX, postY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // move that amount, because how much the position changes depends on the zoom level const deltaX = preX - postX; const deltaY = preY - postY; if (isNaN(deltaX) || isNaN(deltaY)) { return; // abort } // only update within world limits camera.x += deltaX; camera.y += deltaY; // update matrix with new camera updateMatrix(); // prevent further pan if at limits if (atLimits()) { camera.x -= deltaX; camera.y -= deltaY; updateMatrix(); return; // abort } // save current pos for next movement startX = x; startY = y; updateMatrix(); updateTiles(); } handlePan = (startEvent) => { // get position of initial drag [startX, startY] = getClipSpacePosition(startEvent); canvas.style.cursor = 'grabbing'; window.addEventListener('mousemove', handleMove); hammer.on('pan', handleMove); // clear on release const clear = (event) => { canvas.style.cursor = 'grab'; window.removeEventListener('mousemove', handleMove); window.removeEventListener('mouseup', clear); hammer.off('pan', handleMove); hammer.off('panend', clear); }; window.addEventListener('mouseup', clear); hammer.on('panend', clear); } canvas.addEventListener('mousedown', handlePan); hammer.on('panstart', handlePan); // handle zoom events handleZoom = (wheelEvent) => { wheelEvent.preventDefault(); const [x, y] = getClipSpacePosition(wheelEvent); // get position before zooming const [preZoomX, preZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // update current zoom state const prevZoom = camera.zoom; const zoomDelta = -wheelEvent.deltaY * (1 / 500); camera.zoom += zoomDelta; camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM)); updateMatrix(); // prevent further zoom if at limits if (atLimits()) { camera.zoom = prevZoom updateMatrix(); return; } // get new position after zooming const [postZoomX, postZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // camera needs to be translated the difference of before and after camera.x += preZoomX - postZoomX; camera.y += preZoomY - postZoomY; updateMatrix(); updateTiles(); } canvas.addEventListener('wheel', handleZoom); hammer.on('pinch', handleZoom); // setup slider for the text size controls = document.createElement('label'); controls.className = 'webgl-map-controls'; const sizeLabel = document.createElement('span'); sizeLabel.textContent = `text size: ${textSize}px`; const slider = document.createElement('input'); slider.type = 'range'; slider.min = MIN_TEXT_SIZE; slider.max = MAX_TEXT_SIZE; slider.value = textSize; slider.addEventListener('input', () => { textSize = Number(slider.value); sizeLabel.textContent = `text size: ${textSize}px`; }); controls.append(sizeLabel, slider); canvas.parentElement.appendChild(controls); // setup stats widget stats.showPanel(0); // frame rate statsWidget = stats.dom; statsWidget.style.position = 'absolute'; statsWidget.style.zIndex = '0'; canvas.parentElement.appendChild(statsWidget); }; export const stop = () => { loopRunning = false; window.cancelAnimationFrame(frame); if (!canvas) { return; // not running, nothing to clean up } // clear event handlers canvas.removeEventListener('wheel', handleZoom); canvas.removeEventListener('mousedown', handlePan); hammer.destroy(); // clear DOM elements statsWidget.remove(); controls.remove(); // clear atlas texture gl.deleteTexture(atlasTexture); canvas = null; }; export default run;

The text should now stay sharp as you drag the slider. You'll notice the corners of the letters get a bit rounded at the larger sizes, but it holds up a lot better than before.

Adding a halo

There's one more thing that distance fields make pretty easy. Labels can be hard to read when they're on top of other features, so most maps draw an outline (or halo) around the text.

Since the atlas tells us how far each pixel is from the edge, there's nothing special about 0.5. If we lower the cutoff, the letters just get drawn a bit thicker. So for the halo, we can draw the text twice. First in white with the edge moved out by a couple of pixels, and then again on top with the normal edge.

precision mediump float; uniform sampler2D u_atlas; uniform vec4 u_color; uniform float u_edge; // distance value that counts as the edge of the glyph uniform float u_smoothing; // how much to smooth the edge varying vec2 v_texcoord; void main() { float dist = texture2D(u_atlas, v_texcoord).r; float alpha = smoothstep(u_edge - u_smoothing, u_edge + u_smoothing, dist); gl_FragColor = u_color * alpha; }
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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 import { mat3, vec3 } from 'gl-matrix'; import tilebelt from '@mapbox/tilebelt'; import MercatorCoordinate from './mercator-coordinate'; import Stats from 'stats.js'; import { createShader, createProgram } from './webgl-utils'; import { createSDFAtlas, getTextVertices, FONT_SIZE, SDF_RADIUS } from './text-atlas'; import config from '../config'; ////////////////////// // constants ////////////////////// const TILE_SERVER_URL = `https://maps.ckochis.com/data/v3/{z}/{x}/{y}.pbf?apiKey=${config('mapsApiKey')}`; const TILE_SIZE = 512; const MAX_TILE_ZOOM = 14; const MIN_ZOOM = 0; const MAX_ZOOM = 16; const TEXT_COLOR = [51, 51, 51, 255]; const HALO_COLOR = [255, 255, 255, 255]; const HALO_WIDTH = 2; // in pixels const MIN_TEXT_SIZE = 12; const MAX_TEXT_SIZE = 64; ////////////////////// // shaders ////////////////////// // vertex shader just passes through the position, // no modification to the vertices const vertexShaderSource = ` attribute vec2 a_position; uniform mat3 u_matrix; // 3 X 3 matrix void main() { vec2 position = (u_matrix * vec3(a_position, 1)).xy; gl_Position = vec4(position, 0, 1); } `; // set color via uniform const fragmentShaderSource =` precision mediump float; uniform vec4 u_color; void main() { gl_FragColor = u_color; } `; // text vertex shader moves the anchor with the map, // then offsets each corner of the glyph by a fixed number of pixels const textVertexShaderSource = ` attribute vec2 a_anchor; // position of the label on the map attribute vec2 a_offset; // position of the vertex relative to the anchor (in pixels) attribute vec2 a_texcoord; // position of the vertex in the atlas uniform mat3 u_matrix; // 3 X 3 matrix uniform vec2 u_resolution; // size of the canvas (in pixels) uniform float u_scale; // text size relative to the size in the atlas varying vec2 v_texcoord; void main() { v_texcoord = a_texcoord; vec2 anchor = (u_matrix * vec3(a_anchor, 1)).xy; // convert the offset from pixels to clip space (and flip the y) vec2 offset = a_offset * u_scale / u_resolution * vec2(2, -2); gl_Position = vec4(anchor + offset, 0, 1); } `; // text fragment shader looks up the distance from the atlas, // and fills in the pixel if it's on the inside of the edge const textFragmentShaderSource = ` precision mediump float; uniform sampler2D u_atlas; uniform vec4 u_color; uniform float u_edge; // distance value that counts as the edge of the glyph uniform float u_smoothing; // how much to smooth the edge varying vec2 v_texcoord; void main() { float dist = texture2D(u_atlas, v_texcoord).r; float alpha = smoothstep(u_edge - u_smoothing, u_edge + u_smoothing, dist); gl_FragColor = u_color * alpha; } `; ////////////////////// // map state ////////////////////// let loopRunning = true; let frame; // id of the next animation frame const camera = { x: 0, y: 0, zoom: 0, }; // initial transformation (New York) [camera.x, camera.y] = MercatorCoordinate.fromLngLat([-73.98, 40.72]); camera.zoom = 10.5; // DOM elements let canvas; let controls; let statsWidget; const LAYERS = { water: [180, 240, 250, 255], landcover: [202, 246, 193, 255], park: [202, 255, 193, 255], building: [185, 175, 139, 191], }; // layers to get labels from const LABEL_LAYERS = ['place']; const TILE_BUFFER = 1; // 1 tile in each direction let tiles = {}; // tile -> layers let tilesInView = []; let tileWorker; ////////////////////// // text state ////////////////////// let gl; let atlas; let atlasTexture; let textSize = 16; // in pixels function updateTiles() { const bbox = getBounds(); const z = Math.min(Math.trunc(camera.zoom), MAX_TILE_ZOOM); const minTile = tilebelt.pointToTile(bbox[0], bbox[3], z); const maxTile = tilebelt.pointToTile(bbox[2], bbox[1], z); // tiles visible in viewport tilesInView = []; const [minX, maxX] = [Math.max(minTile[0], 0), maxTile[0]]; const [minY, maxY] = [Math.max(minTile[1], 0), maxTile[1]]; for (let x = minX; x <= maxX; x++) { for (let y = minY; y <= maxY; y++) { tilesInView.push([x, y, z]); } } // load additional tiles outside of viewport let bufferedTiles = []; for (let bufX = minX - TILE_BUFFER; bufX <= maxX + TILE_BUFFER; bufX++) { for (let bufY = minY - TILE_BUFFER; bufY <= maxY + TILE_BUFFER; bufY++) { bufferedTiles.push([bufX, bufY, z]); // buffer in xy direction // load parent tiles 2 levels up bufferedTiles.push(tilebelt.getParent([bufX, bufY, z])); bufferedTiles.push(tilebelt.getParent(tilebelt.getParent([bufX, bufY, z]))); } } // remove dupes from in view let tilesToLoad = [ ...new Set([ ...tilesInView.map(t => t.join('/')), ...bufferedTiles.map(t => t.join('/')) ]) ]; // make sure tiles are in range tilesToLoad = tilesToLoad.filter((tile) => { const [x, y, z] = tile.split('/').map(Number); const N = Math.pow(2, z); const validX = x >= 0 && x < N; const validY = y >= 0 && y < N; const validZ = z >= 0 && z <= MAX_TILE_ZOOM; return validX && validY && validZ; }); tilesToLoad.forEach((tile) => { if (tiles[tile]) { return; // already loaded, no need to fetch } tiles[tile] = []; // temp hold for request // load tiles in worker tileWorker.postMessage({ tile, layers: LAYERS, labelLayers: LABEL_LAYERS, url: TILE_SERVER_URL }); }); } let matrix; function updateMatrix() { const cameraMat = mat3.create(); // translate mat3.translate(cameraMat, cameraMat, [camera.x, camera.y]); // scale const zoomScale = 1 / Math.pow(2, camera.zoom); const widthScale = TILE_SIZE / canvas.width; const heightScale = TILE_SIZE / canvas.height; mat3.scale(cameraMat, cameraMat, [zoomScale / widthScale, zoomScale / heightScale]); // update matrix matrix = mat3.multiply( [], mat3.create(), // identity matrix mat3.invert([], cameraMat) // invert camera position ); } // build the text vertices for all of the labels in a tile layer function createTextVertices(labels) { const anchors = []; const offsets = []; const texcoords = []; labels.forEach(({ text, position }) => { const vertices = getTextVertices(atlas, text, position); anchors.push(...vertices.anchors); offsets.push(...vertices.offsets); texcoords.push(...vertices.texcoords); }); return { anchors: Float32Array.from(anchors), offsets: Float32Array.from(offsets), texcoords: Float32Array.from(texcoords), }; } ////////////////////// // helpers ////////////////////// function getClipSpacePosition(e) { // handle mouse and touch events const [x, y] = [ e.center?.x || e.clientX, e.center?.y || e.clientY ]; // get canvas relative css position const rect = canvas.getBoundingClientRect(); const cssX = x - rect.left; const cssY = y - rect.top; // get normalized 0 to 1 position across and down canvas const normalizedX = cssX / canvas.clientWidth; const normalizedY = cssY / canvas.clientHeight; // convert to clip space const clipX = normalizedX * 2 - 1; const clipY = normalizedY * -2 + 1; return [clipX, clipY]; } // get bbox coordinates for viewport function getBounds() { const zoomScale = Math.pow(2, camera.zoom); // undo clip-space const px = (1 + camera.x) / 2; const py = (1 - camera.y) / 2; // get world coord in px const wx = px * TILE_SIZE; const wy = py * TILE_SIZE; // get zoom px const zx = wx * zoomScale; const zy = wy * zoomScale; // get bottom-left and top-right pixels let x1 = zx - (canvas.width / 2); let y1 = zy + (canvas.height / 2); let x2 = zx + (canvas.width / 2); let y2 = zy - (canvas.height / 2); // convert to world coords x1 = x1 / zoomScale / TILE_SIZE; y1 = y1 / zoomScale / TILE_SIZE; x2 = x2 / zoomScale / TILE_SIZE; y2 = y2 / zoomScale / TILE_SIZE; // get LngLat bounding box const bbox = [ Math.max(MercatorCoordinate.lngFromMercatorX(x1), -180), Math.max(MercatorCoordinate.latFromMercatorY(y1), -85.05), Math.min(MercatorCoordinate.lngFromMercatorX(x2), 180), Math.min(MercatorCoordinate.latFromMercatorY(y2), 85.05), ]; return bbox; } function atLimits() { const bbox = getBounds(); return bbox[0] === -180 || bbox[1] === -85.05 || bbox[2] === 180 || bbox[3] === 85.05; } ////////////////////// // main program ////////////////////// let hammer; let handlePan; let handleZoom; let timestamp; let slowCount; const run = (canvasId, abort) => { // setup loop state loopRunning = true; timestamp = 0; slowCount = 0; // create stats object for widget const stats = new Stats(); // get GL context from canvas canvas = document.getElementById(canvasId); gl = canvas.getContext("webgl"); // create the font atlas // (only once, glyphs are added to it as the labels get loaded) if (!atlas) { atlas = createSDFAtlas(); } atlas.dirty = true; // needs to be loaded into the texture // setup tile worker if (!tileWorker) { tileWorker = new Worker(new URL('./text-tile-worker.js', import.meta.url)); tileWorker.onmessage = (event) => { const { tile, tileData } = event.data; // convert the labels in the tile to text vertices (tileData || []).forEach((tileLayer) => { if (tileLayer.labels) { tileLayer.text = createTextVertices(tileLayer.labels); } }); tiles[tile] = tileData; }; tileWorker.onerror = (error) => { console.error('Uncaught worker error.', error); }; } // setup initial state updateMatrix(); updateTiles(); // setup viewport gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); gl.clearColor(0, 0, 0, 0); // init gl program for the map layers const program = createProgram( gl, createShader(gl, gl.VERTEX_SHADER, vertexShaderSource), createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource), ); const positionAttributeLocation = gl.getAttribLocation(program, "a_position"); const matrixLocation = gl.getUniformLocation(program, "u_matrix"); const colorLocation = gl.getUniformLocation(program, "u_color"); // init gl program for the text const textProgram = createProgram( gl, createShader(gl, gl.VERTEX_SHADER, textVertexShaderSource), createShader(gl, gl.FRAGMENT_SHADER, textFragmentShaderSource), ); const anchorAttributeLocation = gl.getAttribLocation(textProgram, "a_anchor"); const offsetAttributeLocation = gl.getAttribLocation(textProgram, "a_offset"); const texcoordAttributeLocation = gl.getAttribLocation(textProgram, "a_texcoord"); const textMatrixLocation = gl.getUniformLocation(textProgram, "u_matrix"); const resolutionLocation = gl.getUniformLocation(textProgram, "u_resolution"); const scaleLocation = gl.getUniformLocation(textProgram, "u_scale"); const atlasLocation = gl.getUniformLocation(textProgram, "u_atlas"); const textColorLocation = gl.getUniformLocation(textProgram, "u_color"); const edgeLocation = gl.getUniformLocation(textProgram, "u_edge"); const smoothingLocation = gl.getUniformLocation(textProgram, "u_smoothing"); // create buffers const positionBuffer = gl.createBuffer(); const anchorBuffer = gl.createBuffer(); const offsetBuffer = gl.createBuffer(); const texcoordBuffer = gl.createBuffer(); // create a texture for the font atlas atlasTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, atlasTexture); 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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // load data into a buffer, and tell the attribute how to get data out of it // (every attribute is 2 floats per vertex) const setAttribute = (location, buffer, data) => { gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); gl.enableVertexAttribArray(location); const size = 2; const type = gl.FLOAT; const normalize = false; const stride = 0; const offset = 0; gl.vertexAttribPointer(location, size, type, normalize, stride, offset); }; // render the map layers for the tiles in view const drawTiles = () => { gl.useProgram(program); // set matrix as uniform gl.uniformMatrix3fv(matrixLocation, false, matrix); tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { layer, vertices } = tileLayer; if (LAYERS[layer] && vertices) { const color = LAYERS[layer].map(n => n / 255); // set color uniform for layer gl.uniform4fv(colorLocation, color); // load vertices for layer setAttribute(positionAttributeLocation, positionBuffer, vertices); // draw const primitiveType = gl.TRIANGLES; const offset = 0; const count = vertices.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // render the labels for the tiles in view const drawLabels = (color, edge) => { gl.uniform4fv(textColorLocation, color.map(n => n / 255)); gl.uniform1f(edgeLocation, edge); tilesInView.forEach((tile) => { const tileData = tiles[tile.join('/')]; (tileData || []).forEach((tileLayer) => { const { text } = tileLayer; if (text && text.anchors.length > 0) { // load vertices for labels setAttribute(anchorAttributeLocation, anchorBuffer, text.anchors); setAttribute(offsetAttributeLocation, offsetBuffer, text.offsets); setAttribute(texcoordAttributeLocation, texcoordBuffer, text.texcoords); // draw const primitiveType = gl.TRIANGLES; const offset = 0; const count = text.anchors.length / 2; gl.drawArrays(primitiveType, offset, count); } }); }); }; // render the text on top of the map const drawText = () => { gl.useProgram(textProgram); // reload the atlas if any glyphs have been added gl.bindTexture(gl.TEXTURE_2D, atlasTexture); if (atlas.dirty) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, atlas.canvas); atlas.dirty = false; } // blend the text with what's already been drawn gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); // set uniforms const scale = textSize / FONT_SIZE; gl.uniformMatrix3fv(textMatrixLocation, false, matrix); gl.uniform2f(resolutionLocation, canvas.width, canvas.height); gl.uniform1f(scaleLocation, scale); gl.uniform1i(atlasLocation, 0); // texture unit 0 // the distance changes by (1 / SDF_RADIUS) for each pixel in the atlas, // so this is how much it changes for each pixel on the screen const pixel = 1 / (SDF_RADIUS * scale); gl.uniform1f(smoothingLocation, 0.7 * pixel); // smooth the edge over about a pixel // draw the halo first by moving the edge out, then the text on top of it drawLabels(HALO_COLOR, 0.5 - HALO_WIDTH * pixel); drawLabels(TEXT_COLOR, 0.5); // reset for the map layers gl.disable(gl.BLEND); gl.disableVertexAttribArray(anchorAttributeLocation); gl.disableVertexAttribArray(offsetAttributeLocation); gl.disableVertexAttribArray(texcoordAttributeLocation); }; const draw = () => { stats.begin(); drawTiles(); drawText(); // kill loop if gets too slow // 10 frames under 10 FPS const now = performance.now(); const fps = 1 / ((now - timestamp) / 1000); if (fps < 10) { slowCount++; if (slowCount > 10) { console.warn(`Too slow. Killing loop for ${canvasId}.`); stop(); if (abort) { abort(); } } } timestamp = now; // end of loop stats.end(); if (loopRunning) { frame = window.requestAnimationFrame(draw); } } frame = window.requestAnimationFrame(draw); // start loop //////////////////////// // interaction handlers //////////////////////// // handle touch events const Hammer = require('hammerjs'); hammer = new Hammer(canvas); hammer.get('pan').set({ direction: Hammer.DIRECTION_ALL }); hammer.get('pinch').set({ enable: true }); // handle pan events let startX; let startY; // handle drag changes while mouse is still down const handleMove = (moveEvent) => { const [x, y] = getClipSpacePosition(moveEvent); // compute the previous position in world space const [preX, preY] = vec3.transformMat3( [], [startX, startY, 0], mat3.invert([], matrix) ); // compute the new position in world space const [postX, postY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // move that amount, because how much the position changes depends on the zoom level const deltaX = preX - postX; const deltaY = preY - postY; if (isNaN(deltaX) || isNaN(deltaY)) { return; // abort } // only update within world limits camera.x += deltaX; camera.y += deltaY; // update matrix with new camera updateMatrix(); // prevent further pan if at limits if (atLimits()) { camera.x -= deltaX; camera.y -= deltaY; updateMatrix(); return; // abort } // save current pos for next movement startX = x; startY = y; updateMatrix(); updateTiles(); } handlePan = (startEvent) => { // get position of initial drag [startX, startY] = getClipSpacePosition(startEvent); canvas.style.cursor = 'grabbing'; window.addEventListener('mousemove', handleMove); hammer.on('pan', handleMove); // clear on release const clear = (event) => { canvas.style.cursor = 'grab'; window.removeEventListener('mousemove', handleMove); window.removeEventListener('mouseup', clear); hammer.off('pan', handleMove); hammer.off('panend', clear); }; window.addEventListener('mouseup', clear); hammer.on('panend', clear); } canvas.addEventListener('mousedown', handlePan); hammer.on('panstart', handlePan); // handle zoom events handleZoom = (wheelEvent) => { wheelEvent.preventDefault(); const [x, y] = getClipSpacePosition(wheelEvent); // get position before zooming const [preZoomX, preZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // update current zoom state const prevZoom = camera.zoom; const zoomDelta = -wheelEvent.deltaY * (1 / 500); camera.zoom += zoomDelta; camera.zoom = Math.max(MIN_ZOOM, Math.min(camera.zoom, MAX_ZOOM)); updateMatrix(); // prevent further zoom if at limits if (atLimits()) { camera.zoom = prevZoom updateMatrix(); return; } // get new position after zooming const [postZoomX, postZoomY] = vec3.transformMat3( [], [x, y, 0], mat3.invert([], matrix) ); // camera needs to be translated the difference of before and after camera.x += preZoomX - postZoomX; camera.y += preZoomY - postZoomY; updateMatrix(); updateTiles(); } canvas.addEventListener('wheel', handleZoom); hammer.on('pinch', handleZoom); // setup slider for the text size controls = document.createElement('label'); controls.className = 'webgl-map-controls'; const sizeLabel = document.createElement('span'); sizeLabel.textContent = `text size: ${textSize}px`; const slider = document.createElement('input'); slider.type = 'range'; slider.min = MIN_TEXT_SIZE; slider.max = MAX_TEXT_SIZE; slider.value = textSize; slider.addEventListener('input', () => { textSize = Number(slider.value); sizeLabel.textContent = `text size: ${textSize}px`; }); controls.append(sizeLabel, slider); canvas.parentElement.appendChild(controls); // setup stats widget stats.showPanel(0); // frame rate statsWidget = stats.dom; statsWidget.style.position = 'absolute'; statsWidget.style.zIndex = '0'; canvas.parentElement.appendChild(statsWidget); }; export const stop = () => { loopRunning = false; window.cancelAnimationFrame(frame); if (!canvas) { return; // not running, nothing to clean up } // clear event handlers canvas.removeEventListener('wheel', handleZoom); canvas.removeEventListener('mousedown', handlePan); hammer.destroy(); // clear DOM elements statsWidget.remove(); controls.remove(); // clear atlas texture gl.deleteTexture(atlasTexture); canvas = null; }; export default run;

The labels should now be a bit easier to read where they overlap the water & parks.

There's still a lot missing here. Nothing is stopping the labels from overlapping each other, and we're only handling labels that sit at a single point (road names need to follow along a line). The text is also laid out one character at a time from left to right, which doesn't work for every language. Those are probably topics for another article.

If you have any questions or comments, feel free to get in touch.

Mapping data is provided by OpenStreetMap contributors.