事件处理程序中的 webGL 绘制似乎清除了画布 [英] webGL draw in event handler seems to clear the canvas

查看:25
本文介绍了事件处理程序中的 webGL 绘制似乎清除了画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个来自 webglfundamentals.com 的简单修改的​​介绍性示例.

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

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

在画布上按下鼠标以绘制新矩形.先前绘制的矩形被清除.为什么?for 循环和事件处理程序正在调用完全相同的函数.

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.

相关代码:

// 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 );
});

我发现使用 preserveDrawingBuffer 初始化上下文会导致鼠标按下矩形绘制在现有矩形的顶部:

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
} );

但我也读到 preserveDrawingBuffer 的性能很差,这并不能完全解释为什么循环内调用和 mousedown 调用呈现不同.

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.

推荐答案

使用 preserveDrawingBuffer: true

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

详情在此鼠标点击后WebGL绘制失败

这篇关于事件处理程序中的 webGL 绘制似乎清除了画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆