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
details here WebGL drawing failure after mouse click