title: Drawing a grid in a WebGL fragment shader
body: <p>I'm working on porting a ZUI from SVG over to WebGL for a few reasons, and I'd like to render a grid using a fragment shader.</p>
  
  <p>Here's the basic effect I'm going for <a href="https://dl.dropboxusercontent.com/u/412963/steel/restel_2.mp4" rel="nofollow noreferrer">https://dl.dropboxusercontent.com/u/412963/steel/restel_2.mp4</a></p>
  
  <p>I'd like to have a triangle that has thin, <strong>1px</strong> lines every 10 units, and a thicker <strong>2px</strong> line every 100 units (the units here being arbitrary but consistent with world-space, not screen-space).</p>
  
  <p>Here's what I have so far, without the secondary thicker lines like in the video (note that this is literally a copy from my open buffer, and obviously isn't right):</p>
  
  <p>Vertex Shader:</p>
  
  <pre><code>attribute vec3 aVertexPosition;
  
  uniform mat4 uMVMatrix;
  uniform mat4 uPMatrix;
  
  varying float vX;
  varying float vY;
  
  void main(void) {
    vX = aVertexPosition.x;
    vY = aVertexPosition.y;
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
  }
  </code></pre>
  
  <p>Fragment Shader:</p>
  
  <pre><code>precision mediump float;
  
  uniform vec2 resolution;
  uniform float uZoomFactor;
  
  varying float vX;
  varying float vY;
  
  void main(void) {
    float distance = gl_FragCoord.z / gl_FragCoord.w;
    float fuzz = 1.0 / distance;
  
    float minorLineFreq;
  
    if (distance &gt; 10.0) {
      minorLineFreq = 1.0;
    } else if (distance &gt; 5.0) {
      minorLineFreq = 1.0;
    } else {
      minorLineFreq = 0.10;
    }
  
    float xd = mod(vX, minorLineFreq) * 88.1;
    float yd = mod(vY, minorLineFreq) * 88.1;
  
    if (xd &lt; fuzz) {
      gl_FragColor = vec4(0.0,0.0,0.0,1.0);
    } else if (yd &lt; fuzz) {
      gl_FragColor = vec4(0.0,0.0,0.0,1.0);
    } else {
      gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
    }
  }
  </code></pre>
  
  <p>It produces approximately the right image at a certain distance (but notice the banding effect where there's 2px lines instead of 1px):</p>
  
  <p><strong>Grid with banding</strong>
  <img src="https://i.stack.imgur.com/vdQQq.png" alt="Grid with banding">
  <strong>Zoomed in grid with unwanted thicker lines</strong>
  <img src="https://i.stack.imgur.com/RzSsF.png" alt="Zoomed in grid with unwanted thicker lines"></p>
  
  <p>So, how can I get a consistent grid, with 1px thick lines at every distance, all inside of a WebGL fragment shader?</p>