【零基础】充分理解WebGL(五)

接上篇 juejin.cn/post/710598…

极坐标

前面的绘图,我们采用的都是直角坐标系,我们可以用坐标变换,将坐标系从直角坐标转换为极坐标。

vec2 polar(vec2 st, vec2 c) {
  vec2 p = c - st;
  float r = length(p) * 2.0;
  float a = atan(p.y, p.x);

  return vec2(r, a);  
}
复制代码

上面的代码以另一种方式绘制了一个圆,它把直角坐标x、y转成到圆心vec2(0.5)为极点的极坐标。

用这个思路,我们可以绘制出一堆有意思的小图形,比如叶片:

float shape_blade(vec2 st, vec2 center, float num) {
  vec2 pt = polar(st, vec2(center));
  float x = pt.x;
  float y = cos(pt.y * num);
  return smoothstep(x - 0.01, x + 0.01, y);  
}
复制代码

还有类似的:

float shape_clover(vec2 st, vec2 center, float num) {
  vec2 pt = polar(st, vec2(center));
  float x = pt.x;
  float y = abs(cos(pt.y * num * 0.5));
  return smoothstep(x - 0.01, x + 0.01, y);  
}
复制代码

以及:

float shape_bud(vec2 st, vec2 center, float num) {
  vec2 pt = polar(st, vec2(center));
  float x = pt.x;
  float y = smoothstep(-0.5, 1.0, cos(pt.y * num)) * 0.2 + 0.5;
  return smoothstep(x - 0.01, x + 0.01, y);  
}
复制代码

还有其他的有趣小图案比如:

float shape_flower(vec2 st, vec2 center, float num) {
  vec2 pt = polar(st, vec2(center));
  float x = pt.x;
  float y = abs(cos(pt.y * num * 0.5)) * 0.5 + 0.3;
  return smoothstep(x - 0.01, x + 0.01, y);  
}
float shape_gourd(vec2 st, vec2 center) {
  return shape_flower(vec2(st.y, st.x), center, 1.7);
}
float shape_apple(vec2 st, vec2 center) {
  return shape_clover(vec2(st.y - 0.2, st.x), center, 1.3);
}
float shape_infinity(vec2 st, vec2 center) {
  return shape_blade(st, center, 2.0);
}
复制代码

我们对极坐标应用上一节学过的重复,还会更加有趣:

void main() {
  vec2 st = gl_FragCoord.xy / resolution;
  vec2 pt = polar(st, vec2(0.5));
  pt = fract(pt * sin(count) * 10.0);
  float x = pt.x;
  float y = abs(cos(pt.y * 3.0 * 0.5)) * 0.5 + 0.3;
  float d = smoothstep(x - 0.01, x + 0.01, y);  
  FragColor.rgb = stroke(1.0 - d, 0.0, 1.0, 0.05) * vec3(1.0);
  FragColor.a = 1.0;
}
复制代码

这一节主要以演示效果为主,理论很简单,就只是把直角坐标转换为极坐标,但是我们发现这种简单的坐标转换,会衍生出很有趣的图形。

你可以把前面的这些例子中的代码参数修改一下,多尝试几下,看看还会出现什么效果。如果你发现了更有意思的效果,可以分享到评论区里。

猜你喜欢

转载自juejin.im/post/7108674503101661197