我将一个简单的 WebGL 示例移植到 Transcrypt(请参见下面的代码),以进行尝试,它确实有效!除了一个细节;似乎 gl.clear() 调用以某种方式没有正确翻译,因为它在 Firefox 中给出了以下错误:
TypeError: gl.py_clear is not a function
注释掉该行会使示例工作。
Python:
from org.transcrypt.stubs.browser import document, __new__
def make_shader(gl, vs, fs):
prog = gl.createProgram()
def add_shader(type_, source):
s = gl.createShader(gl.VERTEX_SHADER
if (type_ == 'vertex')
else gl.FRAGMENT_SHADER)
gl.shaderSource(s, source)
gl.compileShader(s)
if not gl.getShaderParameter(s, gl.COMPILE_STATUS):
return
gl.attachShader(prog, s)
add_shader('vertex', vs)
add_shader('fragment', fs)
gl.linkProgram(prog)
if not gl.getProgramParameter(prog, gl.LINK_STATUS):
raise RuntimeError("Could not link the shader program!")
return prog
def attribute_set_floats(gl, prog, attr_name, rsize, arr):
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer())
gl.bufferData(gl.ARRAY_BUFFER, __new__(Float32Array(arr)),
gl.STATIC_DRAW)
attr = gl.getAttribLocation(prog, attr_name)
gl.enableVertexAttribArray(attr)
gl.vertexAttribPointer(attr, rsize, gl.FLOAT, False, 0, 0)
def draw():
gl = document.getElementById("webgl").getContext("webgl")
gl.clearColor(0.8, 0.8, 0.8, 1.0)
gl.clear(gl.COLOR_BUFFER_BIT) # <- error!
prog = make_shader(gl,
("attribute vec3 pos;"
"void main() {"
" gl_Position = vec4(pos, 2.0);"
"}"),
("void main() {"
" gl_FragColor = vec4(0.5, 0.5, 1.0, 1.0);"
"}"))
gl.useProgram(prog)
attribute_set_floats(gl, prog, "pos", 3, [
-1, 0, 0,
0, 1, 0,
0, -1, 0,
1, 0, 0
])
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
draw()
html:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Example</title>
</head>
<body>
<canvas id="webgl" width="640" height="480"></canvas>
<script type="text/javascript" src="__javascript__/webgl.js">
</script>
</body>
</html>