Skip to content

Commit d5307a2

Browse files
committed
Intro to webgl and shaders
1 parent 8a1ec34 commit d5307a2

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

intro-to-webgl-and-shaders/README.md

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Intro to WebGL and Shaders
2+
3+
> [https://youtu.be/XNbtwyWh9HA](https://youtu.be/XNbtwyWh9HA)
4+
5+
Install [io.js](https://iojs.org/en/index.html).
6+
7+
Within this folder run the terminal command `npm install` to install the
8+
`dependencies` and `devDependencies`.
9+
10+
Then run `npm start` to build as you edit files while viewing `http://localhost:9966`

intro-to-webgl-and-shaders/index.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
var canvas = document.createElement('canvas')
2+
canvas.width = window.innerWidth
3+
canvas.height = window.innerHeight
4+
document.body.appendChild(canvas)
5+
6+
var gl = canvas.getContext('webgl')
7+
8+
gl.clearColor(1, 0, 1, 1)
9+
gl.clear(gl.COLOR_BUFFER_BIT)
10+
11+
var vertexShader = gl.createShader(gl.VERTEX_SHADER)
12+
gl.shaderSource(vertexShader, [
13+
'attribute vec2 position;',
14+
'void main() {',
15+
'gl_Position = vec4(position, 0.0, 1.0);',
16+
'}'
17+
].join('\n'))
18+
gl.compileShader(vertexShader)
19+
20+
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
21+
gl.shaderSource(fragmentShader, [
22+
'precision highp float;',
23+
'uniform vec4 color;',
24+
'void main() {',
25+
'gl_FragColor = color;',
26+
'}'
27+
].join('\n'))
28+
gl.compileShader(fragmentShader)
29+
30+
var program = gl.createProgram()
31+
gl.attachShader(program, vertexShader)
32+
gl.attachShader(program, fragmentShader)
33+
gl.linkProgram(program)
34+
35+
var vertices = new Float32Array([
36+
-0.5,-0.5,
37+
0.5,-0.5,
38+
0.0,0.5
39+
])
40+
41+
var buffer = gl.createBuffer()
42+
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
43+
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
44+
45+
gl.useProgram(program)
46+
program.color = gl.getUniformLocation(program, 'color')
47+
gl.uniform4fv(program.color, [0, 1, 0, 1.0])
48+
49+
program.position = gl.getAttribLocation(program, 'position')
50+
gl.enableVertexAttribArray(program.position)
51+
gl.vertexAttribPointer(program.position, 2, gl.FLOAT, false, 0, 0)
52+
53+
gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 2)
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "intro-to-webgl-and-shaders",
3+
"version": "0.1.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"start": "budo index.js"
8+
},
9+
"author": "Kyle Robinson Young <[email protected]> (http://dontkry.com)",
10+
"license": "MIT",
11+
"devDependencies": {
12+
"budo": "^4.1.0"
13+
}
14+
}

0 commit comments

Comments
 (0)