WebGL offers gl_LINES
as a way to create lines, but you cannot control its thickness. Therefore, I made a shader and some js functionality to create lines using gl_TRIANGLE_STRIP
s. It does make the line thicker, but for some odd reason it contours at the end to give this weird, hair-like shape.
On the image, the top one is the line made using gl_LINES
while the bottom is with gl_TRIANGLE_STRIP
I’d like for the lines to be rendered normally, without a contour but rather a uniform thickness everywhere.
attribute vec4 aPosition;
attribute vec4 aPreviousPosition;
attribute vec4 aNextPosition;
attribute float aDirection;
attribute vec4 aVertexColor;
uniform float uThickness;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying lowp vec4 vColor;
void main(void) {
// shared code begins here
vec4 position = aPosition;
vec4 next = aNextPosition;
vec4 prev = aPreviousPosition;
float thickness = uThickness;
float direction = aDirection;
vec2 tangent = next.xy - prev.xy;
vec2 normal = vec2(-tangent.y, tangent.x);
position.xy += normal * thickness * direction;
gl_Position = uProjectionMatrix * uModelViewMatrix * position;
vColor = aVertexColor;
is the shader code.
My lines are currently objects which have as properties their position buffers and buffers containing the next and previous positions (for the gl_TRIANGLE_STRIP
one only). I generate these vertices using these functions
generateBezierCurvePoints() {
let points = [];
for (let i = 0; i <= this.numberOfPoints; i++) {
let t = i / this.numberOfPoints;
let x =
(1 - t) ** 2 * this.startPoint[0] +
2 * (1 - t) * t * this.controlPoint[0] +
t ** 2 * this.endPoint[0];
let y =
(1 - t) ** 2 * this.startPoint[1] +
2 * (1 - t) * t * this.controlPoint[1] +
t ** 2 * this.endPoint[1];
points.push(x, y);
}
return points;
}
generateLinePoints() {
let pointsBase = this.vertices;
const points = [];
const nextPoints = [];
const prevPoints = [];
const directions = [];
const temp = [];
for (let i = 0; i < pointsBase.length; i += 2) {
// Create a pair with the current element and the next element
const pair = [pointsBase[i], pointsBase[i + 1]];
temp.push(pair);
}
for (let i = 0; i < temp.length; i++) {
const current = temp[i];
const next = temp[i + 1] || current;
const prev = temp[i - 1] || current;
points.push(...current);
nextPoints.push(...next);
prevPoints.push(...prev);
directions.push(1.0);
points.push(...current);
nextPoints.push(...next);
prevPoints.push(...prev);
directions.push(-1.0);
}
gl_LINES (top) versus gl_TRIANGLE_STRIP (bottom) line
Karar Ali is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.