Reputation: 324
I am trying to write a shader material for displaying THREE.Points() objects with rounded points. I am doing this by controlling the alpha value in a fragment shader.
Below is a fully working version of my code. I am getting the desired effect of only colouring pixels within the circle. Outside, however, I am getting white instead of the background colour.
This question is related to mine. I tried setting material.transparent = true
but it did not have any effect.
<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>
Upvotes: 1
Views: 2058
Reputation:
You need to enable alpha blending within the OpenGL context. I am not sure if there is a way to do this using three.js, but adding these GL commands to your render() function will suffice:
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);
};
See the MDN docs on blendFunc for a bit more information on this.
Upvotes: 3