Skip to content

Instantly share code, notes, and snippets.

@talyian
Created June 13, 2017 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save talyian/3b58d888953968e8c2d1f617858fe7ac to your computer and use it in GitHub Desktop.
Save talyian/3b58d888953968e8c2d1f617858fe7ac to your computer and use it in GitHub Desktop.
Mandelbrot set in WebGL
<style>body { background: black; } #cv { display:block; margin:auto; }</style>
<canvas id='cv' width='800' height='800'></canvas>
<script id=frag type='x-shader/fragment'>
precision highp float;
varying vec2 _pos;
void main() {
vec2 c = _pos * 1.5 - vec2(0.7, 0), z;
for(int i = 0; i < 64; i++) {
z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;
gl_FragColor = vec4(vec3((float(i) - log(log(length(z)))) / 64.0), 1);
if (length(z) > 2.0) return;
}
gl_FragColor = vec4(vec3(0), 1);
}
</script>
<script id=vert type='x-shader/vert'>
attribute vec2 pos;
varying vec2 _pos;
void main() { gl_Position = vec4(_pos = pos, 0, 1); }
</script>
<script>
var $ = x => document.getElementById(x);
function draw(gl, program, buffers) {
gl.useProgram(program);
gl.vertexAttribPointer(gl.getAttribLocation(program, "pos"), 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
function initBuffers(gl) {
var buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 1, 1, -1, 1, 1, -1,-1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW);
return buf;
}
function getShader(id) { return [$(id).innerHTML, $(id).type == 'x-shader/fragment' ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER]; }
function compile(gl, src, type) {
var s = gl.createShader(type);
gl.shaderSource(s, src)
gl.compileShader(s);
return s;
}
function program(gl, shaders) {
var p = gl.createProgram();
shaders.map(x => gl.attachShader(p, compile(gl, x[0], x[1])));
gl.linkProgram(p);
gl.enableVertexAttribArray(gl.getAttribLocation(p,"pos"));
return p;
}
var gl = $('cv').getContext('webgl');
draw(gl, program(gl, [getShader('frag'), getShader('vert')]), [initBuffers(gl)])
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment