WebGL:为什么我得到的是拉长的矩形而不是正方形?

WebGL: Why I get the elongated rectangle instead of a square?

WebGL。我尝试通过 WebGL Programming Guide book(第 2 章)得出一个观点。但是我得到了拉长的矩形而不是正方形(Google Chrome v79.0.3945.88 和 Firefox v71.0):

为什么会这样?这是我的代码:

function main(){
    const canvasId = "my-canvas";
    const canvas = document.getElementById(canvasId);
    if(!canvas){
        console.log(`Canvas element with id = '${canvasId}' not found.`);
        return;
    }
    const gl = canvas.getContext("webgl");
    if(!gl){
        console.log(`Can't to get WebGL context.`);
        return;
    }
    gl.clearColor(0.0,1.0,1.0,1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    const vshader_src = `
    void main() {
        gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
        gl_PointSize = 10.0;
    }`;
    const fshader_src = `
    void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }`;
    if(!initShaders(gl, vshader_src, fshader_src)){
        console.log(`Can't initialize shaders.`);
        return;
    }
    gl.drawArrays(gl.POINTS,0,1);
}

我这个例子的完整代码源是here(在src/code/lib/子目录下有书中用到的辅助文件)

您发布的代码中没有错误。

function main(){
    const canvasId = "my-canvas";
    const canvas = document.getElementById(canvasId);
    if(!canvas){
        console.log(`Canvas element with id = '${canvasId}' not found.`);
        return;
    }
    const gl = canvas.getContext("webgl");
    if(!gl){
        console.log(`Can't to get WebGL context.`);
        return;
    }
    gl.clearColor(0.0,1.0,1.0,1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    const vshader_src = `
    void main() {
        gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
        gl_PointSize = 10.0;
    }`;
    const fshader_src = `
    void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }`;
    if(!initShaders(gl, vshader_src, fshader_src)){
        console.log(`Can't initialize shaders.`);
        return;
    }
    gl.drawArrays(gl.POINTS,0,1);
}

// guessed implemenetation of `initShader`
// note this is BAD code. shaders should not be global like this
// The code should be calling `gl.useProgram` outside this
// function as any normal webgl app will have more than one shader program
function initShaders(gl, vsrc, fsrc) {
  const program = twgl.createProgram(gl, [vsrc, fsrc]);
  gl.useProgram(program);
  return program;
}

main();
<canvas id="my-canvas"></canvas>
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>

如果您的 bug 出在其他地方,那么您需要将该代码 放在问题本身中 否则问题因堆栈溢出而脱离主题。

如果 CSS 是 setting the different display size for the canvas

唯一会发生这种情况

我可以建议你阅读 these tutorials