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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With