[Three.js]WebGL心形效果html
WebGL,瀏覽器上的3D技術,基於OpenGL ES 2.0。基礎教程可見Hi,WebGL!、Learning WebGL。git
- function threeStart() {
- initScene();
- initParticles();
- initShape();
- initEmitter();
- animate();
- }
- window.addEventListener('load', threeStart, false);
瀏覽121-147行,THREE .ShaderMaterial的定義,其中attributes, uniforms,對應於GLSL內的變量,其type類型,在WebGLRenderer.js內搜索‘switch ( type )’便可找到。Vertex Shader&Fragment Shader以下:github
- <!-- 頂點着色器 -->
- <script type="x-shader/x-vertex" id="vertexshader">
- attribute float size;
- attribute vec3 ca;
- varying vec3 vColor;
- void main() {
- vColor = ca;
- /*
- * 對於簡單構造的粒子,能夠用一個Object的各頂點表示粒子。
- * 利用gl_PointSize屬性設置每一個粒子大小。更快。
- */
- // 變換後的頂點座標
- vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
- // 頂點大小
- gl_PointSize = size * (200.0 / length(mvPosition.xyz));
- // 輸出頂點世界座標
- gl_Position = projectionMatrix * mvPosition;
- }
- </script>
- <!-- 片元着色器 -->
- <script type="x-shader/x-fragment" id="fragmentshader">
- uniform vec3 color;
- uniform sampler2D texture;
- varying vec3 vColor;
- void main() {
- // 用gl_PointCoord設置紋理,不是UV座標了
- vec4 outColor = texture2D(texture, gl_PointCoord);
- // 設定像素顏色 = 紋理顏色 * 頂點顏色
- gl_FragColor = outColor * vec4(color * vColor.xyz, 1.0);
- // 計算像素世界座標z值
- float depth = gl_FragCoord.z / gl_FragCoord.w;
- // 霧顏色:黑
- const vec3 fogColor = vec3(0.0, 0.0, 0.0);
- // const vec3 fogColor = vec3(0xff, 0xff, 0xff);
- // 霧因素:depth<=200時0,>=600時1
- float fogFactor = smoothstep(200.0, 600.0, depth);
- // 混合霧的像素顏色
- gl_FragColor = mix(gl_FragColor, vec4(fogColor, gl_FragColor.w), fogFactor);
- }
- </script>
- // 沿形狀路線運行
- timeOnShapePath += 0.01;
- if (timeOnShapePath > 1) timeOnShapePath -= 1;
- var pointOnShape = heartShape.getPointAt(timeOnShapePath);
- emitterpos.x = pointOnShape.x * 2 - 50;
- emitterpos.y = -pointOnShape.y * 2 + 100;
- // 設置須要更新
- group.geometry.verticesNeedUpdate = true; // 頂點
- attributes.size.needsUpdate = true; // 大小
- attributes.ca.needsUpdate = true; // 顏色