-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
76 lines (65 loc) · 1.87 KB
/
main.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
import { fetchShader } from "./utils.js"
async function main() {
const vertexShader = await fetchShader("vertex");
const fragmentShader = await fetchShader("fragment");
const body = document.getElementsByTagName("BODY")[0];
const vElem = document.createElement("script");
vElem.id = "vs";
vElem.type = "notjs"
vElem.append(vertexShader);
body.appendChild(vElem);
const fElem = document.createElement("script");
fElem.id = "fs";
fElem.type = "notjs"
fElem.append(fragmentShader);
body.appendChild(fElem);
const gl = document.querySelector("#c").getContext("webgl");
const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);
const arrays = {
position: [-1, -1, 0, 1, -1, 0, -1, 1, 0, -1, 1, 0, 1, -1, 0, 1, 1, 0],
};
const bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);
var cameraX = 1.0;
var cameraY = 2.0;
var cameraZ = 1.0;
document.addEventListener('keydown', (event) => {
if (event.defaultPrevented) {
return;
}
var key = event.key || event.keyCode;
if (key === 'w') {
cameraZ += .1;
}
if (key === 'a') {
cameraX -= .1;
}
if (key === 's') {
cameraZ -= .1;
}
if (key === 'd') {
cameraX += .1;
}
if (key === 'e') {
cameraY += .1;
}
if (key === 'q') {
cameraY -= .1;
}
});
function render(time) {
twgl.resizeCanvasToDisplaySize(gl.canvas);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
const uniforms = {
time: time * 0.001,
resolution: [gl.canvas.width, gl.canvas.height],
cameraPosition: [cameraX, cameraY, cameraZ]
};
gl.useProgram(programInfo.program);
twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);
twgl.setUniforms(programInfo, uniforms);
twgl.drawBufferInfo(gl, bufferInfo);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();