webGL draw in event handler seems to clear the can

2019-08-22 04:31发布

Here is a very lightly reworked introductory example from webglfundamentals.com.

http://codepen.io/anon/pen/mVYrZd

Mousedown on the canvas to draw a new rectangle. The previously drawn rectangles are cleared. Why? The for loop and the event handler are calling the exact same function.

Relevant code:

// Draw 50 random rectangles in random colors.
// They draw on top of each other, as expected.
for ( var i = 0; i < 50; i += 1 ) {
  drawARandomRectangle( gl );
}

// Draw one rectangle on the canvas in response to a canvas mousedown.
// The buffer seems to be cleared, only a single new rectangle shows.
canvas.addEventListener("mousedown", function( e ){
  drawARandomRectangle( gl );
});

I have figured out that initializing the context with preserveDrawingBuffer causes the mousedown rectangle to be drawn on top of the existing rectangles:

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

But I've also read that the performance of preserveDrawingBuffer is poor, and it doesn't quite explain why the in-loop calls and the mousedown call render differently.

1条回答
The star\"
2楼-- · 2019-08-22 05:12

Use preserveDrawingBuffer: true

var gl = canvas.getContext( "webgl", { antialias: false, preserveDrawingBuffer: true} )

details here WebGL drawing failure after mouse click

查看更多
登录 后发表回答