Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webgl dash line

Can someone tell me how to draw dashed lines in WebGL without using Three.js or any other toolkit? Just plain WebGL. I'm very new to WebGL and I can't seem to find the answer to this question.

like image 357
user2154858 Avatar asked Mar 10 '13 22:03

user2154858


2 Answers

There are no native stippled lines in WebGL (or OpenGL ES) but the effect is easy to achieve with a fragment shader, if you include a "length so far" vertex attribute in your VBO.

precision highp float;
varying float LengthSoFar; // <-- passed in from the vertex shader
const vec3 Color = vec3(1, 1, 1);
const float NumDashes = 10.0; // 10 dashes for every 1 unit in LengthSoFar

void main()
{
    float alpha = floor(2.0 * fract(LengthSoFar * NumDashes));
    gl_FragColor = vec4(Color, alpha);
}

An alternative method would be to make a lookup into a 1D texture. The length-so-far attribute is really just a 1D texture coordinate.

like image 109
prideout Avatar answered Sep 22 '22 15:09

prideout


Something that I've done in the past, though it may not meet your use case, is to create a vertex buffer containing the points of a path, then draw it using

gl.drawArrays(gl.LINES, 0, vertexCount);

Using gl.LINES naturally "skips" every other segment of the path, creating a dashed effect if the path points are frequent enough. It's simple and hacky, but effective in the right circumstances.

like image 23
Toji Avatar answered Sep 24 '22 15:09

Toji