shader 画圆,椭圆
@
目录
概述
记录一下如何使用shader来画圆
let shader = {
vs: `
varying vec2 v_uv;
void main() {
v_uv = uv;
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4( position, 1.0 );
}
`,
fs: `
varying vec2 v_uv;
uniform float u_time;
void main() {
vec3 bcol = vec3(0.29412, 0.70196, 0.63921) * (1.0 - 0.6 * length(v_uv));
// 原理:根据uv值来计算到原点的距离,大于半径值即在圆外,小于半径值在圆内
float pct = distance(vec2(0.5,0.5), v_uv);
// 椭圆
// pct = distance(v_uv,vec2(0.470,0.600)) + distance(v_uv,vec2(0.570,0.540));
//两个圆相吸
// pct = distance(v_uv,vec2(0.550,0.520)) * distance(v_uv,vec2(0.010,0.040));
//两个圆
// pct = min(distance(v_uv,vec2(0.140,0.130)),distance(v_uv,vec2(0.660,0.600)));
//两个圆相交部分 - 可以用来做遮罩
// pct = max(distance(v_uv,vec2(0.550,0.590)),distance(v_uv,vec2(0.6)));
//半径
float radius = 0.1;
// smoothstep(a, b, x)可以用来生成0到1的平滑过渡. 如果a > b 那x为1-》0过渡 ,如果a<b,那位0=》1过渡
float col = smoothstep(radius + 0.008, radius, pct) ;
gl_FragColor = vec4(vec3(col + bcol), 1.0);
}
`,
uniform: {
u_time: {
value: 0.0
}
}
}
let geometry = new THREE.PlaneGeometry(20, 20);
let material = new THREE.ShaderMaterial({
vertexShader: shader.vs,
fragmentShader: shader.fs,
uniforms: shader.uniform,
transparent: true
})
let mesh = new THREE.Mesh(geometry, material);
// mesh.rotateX(-Math.PI / 2);
scene.add(mesh);