【问题标题】:WebGL: Why I get the elongated rectangle instead of a square?WebGL:为什么我得到的是细长的矩形而不是正方形?
【发布时间】:2019-12-22 18:12:53
【问题描述】:

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/子目录下有书中用到的辅助文件)。

【问题讨论】:

标签: javascript webgl


【解决方案1】:

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

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>

如果您的错误在其他地方,那么您需要将该代码放在问题本身中,否则问题与堆栈溢出无关。

如果 CSS 是 setting the different display size for the canvas,则唯一可以实现这一点。

我建议你阅读these tutorials

【讨论】:

  • 你是对的,这种行为的原因是 CSS 风格。问题已经解决了。感谢您提供有用的链接! ?
猜你喜欢
  • 2016-10-06
  • 2016-01-30
  • 1970-01-01
  • 2011-11-18
  • 2016-06-21
  • 2018-07-07
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多