WebGL context is redrawn completely for no apparent reason

老子叫甜甜 提交于 2021-02-10 20:12:49

问题


I'm experimenting with WebGL and it seems to me that I've missing something very basic but still can not find in docs and examples what exactly. So imagine I want to draw a rectangle, id do something like this:

let points = rectangle(20, 20, 100, 100)
gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, convertFloat32(points), WebGLRenderingContext.STATIC_DRAW)
gl.drawArrays(WebGLRenderingContext.LINE_STRIP, 0, points.length)

This works. I see a rectangle drawn an cannot be more happier. Same holds true about drawing as many rectangles as I want to.

However, whenever I'm trying to add something like this:

window.setTimeout(function() {
    let points = rectangle(120, 120, 100, 100)
    gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, convertFloat32(points), WebGLRenderingContext.STATIC_DRAW)
    gl.drawArrays(WebGLRenderingContext.LINE_STRIP, 0, points.length)
}, 1000);

or, say to draw rectangles in some DOM event handler, all that previously has been drawn is erased and I have no clue why.

My question would be - what do I missing exactly?

UPD: I've forked some existing example and modified it to have (sort of) minimal example of what I'm talking about - https://codepen.io/shabunc/pen/YRgzJq?editors=1010


回答1:


There is a a second argument - some optional parameters - for the getCcontext() method.

In Your example, try adding following lines of code:

var canvas = document.getElementById("c");

var NO_ANTIALIAS = false, 
    CLEAR_DRAWING_BUFFER = false,
    attributes = {antialias: !NO_ANTIALIAS, preserveDrawingBuffer: !CLEAR_DRAWING_BUFFER};

var gl = canvas.getContext("webgl", attributes);

Explanation:

  • antialias: this is just a hint for the browser - when available, try to smooth drawing borders
  • preserveDrawingBuffer: You need to take care of clearing the drawing buffer by Your self

Here is the reference: WebGL Specification - Context creation



来源:https://stackoverflow.com/questions/53580879/webgl-context-is-redrawn-completely-for-no-apparent-reason

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