问题
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