简体   繁体   中英

webGL draw in event handler seems to clear the canvas

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.

Use preserveDrawingBuffer: true

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

details here WebGL drawing failure after mouse click

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM