webGL draw in event handler seems to clear the canvas

走远了吗. 提交于 2019-12-11 13:56:04

问题


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:


Use preserveDrawingBuffer: true

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

details here WebGL drawing failure after mouse click



来源:https://stackoverflow.com/questions/35493509/webgl-draw-in-event-handler-seems-to-clear-the-canvas

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