WebGL drawing failure after mouse click

家住魔仙堡 提交于 2020-01-07 03:58:47

问题


I have a helper method drawRect(p1, p2) that draws a rectangle (in orthographic projection). The code works fine if I do this:

function webGLStart() {
    // initialization code

    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.uniformMatrix4fv(shaderProgram.pMatrixLoc, false, pMatrix);

    drawRect(new Point(10, 10), new Point(50, 50));
}

Now suppose I want to render a new rectangle after every mouse click. So I cleared the canvas, set up the projection matrix and moved the drawRect call in mouse down handler. And it is not working.

function webGLStart() {
    // initialization code

    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.uniformMatrix4fv(shaderProgram.pMatrixLoc, false, pMatrix);

    canvas.onmousedown = handleMouseDown;
}

function handleMouseDown(event) {
    // x, y depends on click coordinate
    drawRect(new Point(x, y), new Point(x + 20, y + 20));
}

The whole canvas is getting vanished after mouse click. However, if I store the information of all rectangles in an array and in mouse handler I clear the canvas and then draw all rectangles from the array then there is no problem. In other words if I re-render the complete scene then there is no problem.

So my question is: is it not possible to draw one after another without clearing the whole canvas and refreshing everything?


回答1:


If you want to "preserve" the background then you must use the preserveDrawingBuffer flag:

gl = canvas.getContext("experimental-webgl", {preserveDrawingBuffer:true} );

See these recent answers:

When WebGL decide to update the display?

Webgl update region using viewport+scissor



来源:https://stackoverflow.com/questions/9843492/webgl-drawing-failure-after-mouse-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!