how to draw perfect line in webgl

2.7k views Asked by At

I want to draw perfect line using webgl. I had not set anything in renderer context. What should I enable or set or give what option to canvas.getContext to help me draw a line which seems good? I think use linear and somethings (I have no idea) to give me a line which is not like stairs.

canvas = document.getElementById('canvas');
canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;
    gl = canvas.getContext('webgl2',{
        antialias: true,
        depth: false,
        stencil: false
    });
    gl.viewport(0,0,canvas.width,canvas.height);



array = {
  pos: {
    numComponents: 2,
    data: [-0.03, -1  ,  0.03, 1],
  },
};

Program = twgl.createProgramInfo(gl, [
  `#version 300 es
    precision highp float;
    in vec2 pos;
    void main(){gl_Position = vec4(pos, 0.0 , 1.0);}`,
  `#version 300 es
    precision highp float;
    out vec4 Color;
    void main(){Color.xyz = vec3(0.0) ; Color.a = 1.0;}
    `
]);
Attrib = twgl.createBufferInfoFromArrays(gl, array);

obj = {
  type: gl.LINES,
  programInfo: Program,
  bufferInfo: Attrib,
  //count: 1
};
requestAnimationFrame(() => twgl.drawObjectList(gl, [obj]));
<canvas id="canvas"></canvas>
<script src="https://twgljs.org/dist/3.x/twgl.min.js"></script>

Thanks in advance.

2

There are 2 answers

5
indexoutofbounds On

I guess by not like stairs you mean aliasing. According to the MDN web docs you can turn on the according flag when retrieving the webgl rendering context.

Assuming you have a canvas like this:

<canvas id="canvas"></canvas>

You can turn on antialiasing by:

var canvas = document.getElementById('canvas');
var gl = canvas.getContext('webgl',
                 { antialias: true });

For further information please read the according documentation.

0
DenisKolodin On

Try to set the better resolution (width and height attributes) than the real size in CSS styles attribute. For example:

Original size:

enter image description here

Size 2x + styles:

<canvas width=800 height=400 styles="width: 400; height: 200;" id="canvas"/>

enter image description here

Both screenshots made from the real screen and not scaled.