0
我想寫一個着色器材質來顯示帶圓角點的THREE.Points()對象。我通過控制片段着色器中的alpha值來做到這一點。使用ShaderMaterial的Alpha顏色
下面是我的代碼的完整工作版本。我獲得了只在圓內着色像素的預期效果。不過,外面,我得到白色,而不是背景顏色。
This 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>
您接受的答案不是如何在three.js中完成。而不是將alpha設置爲零,這樣做:'if(length(gl_PointCoord - vec2(0.5,0.5))> 0.475)discard;' – WestLangley
接受的答案解決了爲ShaderMaterial啓用alpha混合的問題。但是,您的代碼幫助我消除了角落中的奇怪渲染。謝謝。 –
通過設置material.transparent = true,可以在three.js中啓用alpha混合。 – WestLangley