使用ShaderMaterial的Alpha颜色

时间:2015-11-20 01:24:38

标签: three.js webgl

我正在尝试编写一个着色器材质,用于显示带有圆角点的THREE.Points()对象。我这样做是通过控制片段着色器中的alpha值来实现的。

以下是我的代码的完整工作版本。我得到的效果只是在圆圈内着色像素。然而,在外面,我变得白色而不是背景色。

question与我有关。我尝试设置material.transparent = true但它没有任何效果。

    <html>
    <head>
        <title>THREEJS alpha shader</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100% }
        </style>
        <script type="text/javascript" src="http://threejs.org/build/three.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    </head>
    <body>
        <!-- Shaders -->
        <script type="x-shader/x-vertex" id="vertexshader">
            void main() {
                gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
                gl_PointSize = 40.0; // pixels
            }
        </script>

        <script type="x-shader/x-fragment" id="fragmentshader">
            varying vec4 color;

            void main() {
                // radius
                float r = length(gl_PointCoord - vec2(0.5, 0.5));

                if(r < 0.5) {
                    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
                } else {
                    gl_FragColor = vec4(1.0, 1.0, 1.0, 0.0);
                }
            }
        </script>

        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );

            var buffer = new Float32Array(3);   // single point located at (0, 0, 0)
            var geometry = new THREE.BufferGeometry();
            geometry.addAttribute('position', new THREE.BufferAttribute(buffer,3) );

            // create shader material
            var material = new THREE.ShaderMaterial({
                vertexShader : $('#vertexshader').text(),
                fragmentShader : $('#fragmentshader').text(),
                });

            var point = new THREE.Points(geometry, material);
            scene.add(point);
            camera.position.z = 2;

            var render = function () {
                requestAnimationFrame( render );
                renderer.render(scene, camera);
            };
            render();
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要在OpenGL上下文中启用Alpha混合。我不确定是否有办法使用three.js,但将这些GL命令添加到render()函数就足够了:

var render = function () {
  var gl = renderer.context;
  gl.enable(gl.BLEND);
  gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  requestAnimationFrame( render );
  renderer.render(scene, camera);
};

有关详细信息,请参阅blendFunc上的MDN文档。