-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtextcache.js
108 lines (97 loc) · 2.54 KB
/
textcache.js
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
'use strict'
module.exports = textGet
var vectorizeText = require('vectorize-text')
var globals = window || process.global || {}
var __TEXT_CACHE = globals.__TEXT_CACHE || {}
globals.__TEXT_CACHE = {}
function unwrap(mesh) {
var cells = mesh.cells
var positions = mesh.positions
var data = new Float32Array(cells.length * 6)
var ptr = 0
var shapeX = 0
for(var i=0; i<cells.length; ++i) {
var tri = cells[i]
for(var j=0; j<3; ++j) {
var point = positions[tri[j]]
data[ptr++] = point[0]
data[ptr++] = point[1] + 1.4
shapeX = Math.max(point[0], shapeX)
}
}
return {
data: data,
shape: shapeX
}
}
function textGet(font, text, opts) {
var opts = opts || {}
var fontStyle = opts.fontStyle || 'normal'
var fontWeight = opts.fontWeight || 'normal'
var fontVariant = opts.fontVariant || 'normal'
var fontKey = [
fontStyle,
fontWeight,
fontVariant,
font
].join('_')
var fontcache = __TEXT_CACHE[fontKey]
if(!fontcache) {
fontcache = __TEXT_CACHE[fontKey] = {
' ': {
data: new Float32Array(0),
shape: 0.2
}
}
}
var mesh = fontcache[text]
if(!mesh) {
if(text.length <= 1 || !/\d/.test(text)) {
mesh = fontcache[text] = unwrap(vectorizeText(text, {
triangles: true,
font: font,
fontStyle: fontStyle,
fontWeight: fontWeight,
fontVariant: fontVariant,
textAlign: opts.textAlign || 'left',
textBaseline: 'alphabetic',
styletags: {
breaklines: true,
bolds: true,
italics: true,
subscripts: true,
superscripts: true
}
}))
} else {
var parts = text.split(/(\d|\s)/)
var buffer = new Array(parts.length)
var bufferSize = 0
var shapeX = 0
for(var i=0; i<parts.length; ++i) {
buffer[i] = textGet(font, parts[i])
bufferSize += buffer[i].data.length
shapeX += buffer[i].shape
if(i>0) {
shapeX += 0.02
}
}
var data = new Float32Array(bufferSize)
var ptr = 0
var xOffset = -0.5 * shapeX
for(var i=0; i<buffer.length; ++i) {
var bdata = buffer[i].data
for(var j=0; j<bdata.length; j+=2) {
data[ptr++] = bdata[j] + xOffset
data[ptr++] = bdata[j+1]
}
xOffset += buffer[i].shape + 0.02
}
mesh = fontcache[text] = {
data: data,
shape: shapeX
}
}
}
return mesh
}