-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathwebGL.html
More file actions
386 lines (344 loc) · 13.2 KB
/
Copy pathwebGL.html
File metadata and controls
386 lines (344 loc) · 13.2 KB
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
<!doctype html>
<meta charset="utf-8" />
<title>Demo of complex text in WebGL</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"
defer>
</script>
<script src="webGLSetup.js"></script>
<style>
canvas {
border: 1px solid blue;
width: 400px;
height: 600px;
}
#choice {
border: 1px solid blue;
box-sizing: border-box;
width: 400px;
height: 400px;
padding: 10px;
font-size: 3em;
display: flex;
flex-direction: column;
}
#choice label {
display: flex;
align-items: center;
gap: 0.3em;
}
#choice input[type="radio"] {
width: 0.8em;
height: 0.8em;
}
#choice button {
font-size: 0.5em;
margin-top: 0.4em;
padding: 0.2em 0.6em;
}
.message {
border: 1px solid blue;
box-sizing: border-box;
width: 400px;
height: 400px;
padding: 10px;
font-size: 2em;
display: flex;
flex-direction: column;
}
.message button {
font-size: 0.5em;
margin-top: 0.4em;
padding: 0.2em 0.6em;
}
</style>
<!-- Note: content=drawable is the new API and layoutsubtree has been left -->
<!-- only for temporary backwards compatibility. -->
<canvas id="gl-canvas" width="400" height="600" content="drawable" layoutsubtree>
<div drawable id="choice">
<label><input type="radio" id="chk-english" name="language" value="english" checked> English</label>
<label><input type="radio" id="chk-spanish" name="language" value="spanish"> Español</label>
<label><input type="radio" id="chk-hindi" name="language" value="hindi"> हिंदी</label>
<label><input type="radio" id="chk-korean" name="language" value="korean"> 한국어</label>
<button id="flip-btn" onclick="flip()">Flip</button>
</div>
<div drawable id="english" class="message" inert>
<p lang="en">Internationalized text made easy with HTML-in-Canvas</p>
<button onclick="flip()">Flip</button>
</div>
<div drawable id="spanish" class="message" inert>
<p lang="es">Texto internacionalizado hecho fácil con HTML-in-Canvas</p>
<button onclick="flip()">Flip</button>
</div>
<div drawable id="hindi" class="message" inert>
<p lang="hi">HTML-in-Canvas के साथ अंतर्राष्ट्रीयकृत पाठ आसान बना</p>
<button onclick="flip()">Flip</button>
</div>
<div drawable id="korean" class="message" inert>
<p lang="ko">HTML-in-Canvas로 쉬워진 국제화 텍스트</p>
<button onclick="flip()">Flip</button>
</div>
</canvas>
<script>
let canvas_css_width = 400;
let canvas_css_height = 600;
let choice_in_front = true;
let card_rotation = 0.0;
let cardTargetRotation = 0.0;
let currentTime = 0;
let deltaTime = 0;
let render_context = null;
// Determine which element texture is visible
function getVisibleElement() {
if (cardTargetRotation > 0.0) {
choice_in_front = false;
var checked_elmt = document.querySelector('input[name="language"]:checked');
return document.getElementById(checked_elmt.value);
} else {
choice_in_front = true;
return document.getElementById("choice");
}
}
// Update the inert status when the card is flipped. This keeps the
// accessibility information up to date and determines which elements are
// hit tested.
function setInert() {
const messages = ["english", "spanish", "hindi", "korean"];
var visible_element = getVisibleElement();
var choice_elmt = document.getElementById("choice");
if (choice_elmt == visible_element) {
choice_elmt.removeAttribute("inert");
} else {
choice_elmt.setAttribute("inert", true);
}
for (id in messages) {
var elmt = document.getElementById(messages[id]);
if (elmt == visible_element) {
elmt.removeAttribute("inert");
} else {
elmt.setAttribute("inert", true);
}
}
}
// Flip the card, which involves triggering the animation and resetting the
// inert status of elements.
function flip() {
if (cardTargetRotation > 0.0) {
cardTargetRotation = 0.0;
} else {
cardTargetRotation = Math.PI;
}
setInert();
}
function updateElementGeometry(model_to_screen_matrix) {
var top_left = vec4.fromValues(-1, -1, 0.1, 1);
var bottom_right = vec4.fromValues(1, 1, 0.1, 1);
vec4.transformMat4(top_left, top_left, model_to_screen_matrix);
vec4.transformMat4(bottom_right, bottom_right, model_to_screen_matrix);
var gl_screen_rect = new DOMRect();
gl_screen_rect.x = top_left[0] / top_left[3];
gl_screen_rect.y = top_left[1] / top_left[3];
gl_screen_rect.width = bottom_right[0] / bottom_right[3] - gl_screen_rect.x;
gl_screen_rect.height = bottom_right[1] / bottom_right[3] - gl_screen_rect.y;
// The GL rectangle origin (-1,-1) size (2,2) covers the canvas area. Map
// GL coordinates into canvas CSS coordinates.
const canvas = document.querySelector('#gl-canvas');
var canvas_rect = new DOMRect();
canvas_rect.x = (gl_screen_rect.x + 1) * canvas_css_width / 2;
canvas_rect.y = (gl_screen_rect.y + 1) * canvas_css_height / 2;
canvas_rect.width = gl_screen_rect.width * canvas_css_width / 2;
canvas_rect.height = gl_screen_rect.height * canvas_css_height / 2;
// Determine the DOMMatrix transform that maps the element bounding box
// onto the GL rect for the texture area. The element bounding box is
// 400x400.
var visible_elmt = getVisibleElement();
var canvas_transform = new DOMMatrix();
canvas_transform.a = canvas_rect.width / 400;
canvas_transform.d = canvas_rect.height / 400;
canvas_transform.e = canvas_rect.x;
canvas_transform.f = canvas_rect.y;
if (canvas.updateElementGeometry !== undefined) {
// New html-in-canvas approach for updating the element's geometry from
// the canvas transform.
canvas.updateElementGeometry(visible_elmt, {canvasTransform: canvas_transform});
} else {
// Older approach (do not use).
visible_elmt.style.transform = canvas_transform.toString();
}
}
// Create an initial empty texture for binding.
function createEmptyTexture(gl) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Linear texture filtering produces better results than mipmap with text.
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);
return texture;
}
// Draw/update the element's visual onto the specified texture
function updateTexture(gl, texture, element) {
gl.bindTexture(gl.TEXTURE_2D, texture);
const internalFormat = gl.RGBA8;
try {
// Pre-allocate texture backing with pre-determined size.
let elementImage = gl.canvas.captureElementImage(element);
gl.texImage2D(
/* target */ gl.TEXTURE_2D,
/* level */ 0,
/* internalformat */ gl.RGBA8,
/* width */ elementImage.width,
/* height */ elementImage.height,
/* border */ 0,
/* format */ gl.RGBA,
/* type */ gl.UNSIGNED_BYTE,
/* srcData */ null);
gl.texElementSubImage2D(gl.TEXTURE_2D, /*level*/0, /*xoffset*/0, /*yoffset*/0, element);
} catch (e) {
try {
// The texElementImage2D API was recently changed (see:
// https://github.com/WICG/html-in-canvas#idl-changes). This snippet
// supports the old syntax temporarily so that the demos do not break.
const level = 0;
const srcFormat = gl.RGBA;
const destType = gl.UNSIGNED_BYTE;
gl.texElementImage2D(gl.TEXTURE_2D, level, internalFormat,
srcFormat, destType, element);
console.log('Note: using old texElementImage2D API');
} catch (e) {
// The texElementImage2D API was recently changed (see:
// https://github.com/WICG/html-in-canvas#idl-changes). This snippet
// supports the old syntax temporarily so that the demos do not break.
gl.texElementImage2D(gl.TEXTURE_2D, internalFormat, element);
console.log('Note: using old texElementImage2D API');
}
}
}
// Draw the scene
function render() {
let new_time = performance.now() * 0.001; // convert to seconds
deltaTime = new_time - currentTime;
currentTime = new_time;
if (render_context === null) {
return;
}
var model_to_screen_matrix = drawScene(render_context.gl,
render_context.program,
render_context.buffers,
render_context.texture_checkboxes,
render_context.texture_choice,
card_rotation);
updateElementGeometry(model_to_screen_matrix);
if (card_rotation < cardTargetRotation) {
card_rotation += deltaTime;
if (card_rotation > cardTargetRotation) {
card_rotation = cardTargetRotation;
}
} else if (card_rotation > cardTargetRotation) {
card_rotation -= deltaTime;
if (card_rotation < cardTargetRotation) {
card_rotation = cardTargetRotation;
}
}
}
function setupGL() {
const canvas = document.querySelector('#gl-canvas');
// Initialize the GL context
const gl = canvas.getContext('webgl2');
// Only continue if WebGL is available and working
if (gl === null) {
alert(
'Unable to initialize WebGL. Your browser or machine may not support it.',
);
return;
}
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec2 aTextureCoord;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying highp vec2 vTextureCoord;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vTextureCoord = aTextureCoord;
}
`;
// Fragment shader program
const fsSource = `
varying highp vec2 vTextureCoord;
uniform sampler2D uSampler;
void main(void) {
gl_FragColor = texture2D(uSampler, vTextureCoord);
}
`;
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
uSampler: gl.getUniformLocation(shaderProgram, 'uSampler'),
},
};
const buffers = initBuffers(gl);
// Initialize textures without drawing immediately, waiting for onpaint to fill them
const texture_checkboxes = createEmptyTexture(gl);
const texture_choice = createEmptyTexture(gl);
// Flip image pixels into the bottom-to-top order that WebGL expects.
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
render_context = {
gl: gl,
program: programInfo,
buffers: buffers,
texture_checkboxes: texture_checkboxes,
texture_choice: texture_choice,
};
}
onload = () => {
const canvas = document.querySelector('#gl-canvas');
let initialized_gl = false;
let lastLangId = null;
// The main paint event loop.
canvas.onpaint = (event) => {
if (!initialized_gl) {
setupGL();
initialized_gl = true;
}
if (event.changedElements && event.changedElements.length) {
// Convert elements into an array if they are not already to safely use array methods
const changedArray = Array.from(event.changedElements);
const choiceEl = document.getElementById("choice");
const checkedLang = document.querySelector('input[name="language"]:checked');
const langId = checkedLang ? checkedLang.value : "english";
const langEl = document.getElementById(langId);
// Update the checkboxes texture if the choice element changed
if (changedArray.includes(choiceEl)) {
updateTexture(render_context.gl, render_context.texture_checkboxes, choiceEl);
}
// Update the choice texture if its content changed, or if the user selected a new language
if (changedArray.includes(langEl) || langId !== lastLangId) {
updateTexture(render_context.gl, render_context.texture_choice, langEl);
lastLangId = langId;
}
}
render();
// Loop to continuously fire canvas paint events.
canvas.requestPaint();
}
canvas.requestPaint();
const observer = new ResizeObserver(([entry]) => {
canvas.width = entry.devicePixelContentBoxSize[0].inlineSize;
canvas.height = entry.devicePixelContentBoxSize[0].blockSize;
canvas_css_width = entry.contentBoxSize[0].inlineSize;
canvas_css_height = entry.contentBoxSize[0].blockSize;
});
observer.observe(canvas, {box: 'device-pixel-content-box'});
}
</script>