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

語言: CN / TW / HK

接上篇 https://juejin.cn/post/7105980140747751460

極座標

前面的繪圖,我們採用的都是直角座標系,我們可以用座標變換,將座標系從直角座標轉換為極座標。

```glsl 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);
} ```

https://code.juejin.cn/pen/7108656624918593544

上面的程式碼以另一種方式繪製了一個圓,它把直角座標x、y轉成到圓心vec2(0.5)為極點的極座標。

用這個思路,我們可以繪製出一堆有意思的小圖形,比如葉片:

glsl 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); }

https://code.juejin.cn/pen/7108661056653754405

還有類似的:

glsl 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); }

https://code.juejin.cn/pen/7108664566455730189

以及:

glsl 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); }

https://code.juejin.cn/pen/7108665643573968927

還有其他的有趣小圖案比如:

glsl 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); }

https://code.juejin.cn/pen/7108669584722526221

我們對極座標應用上一節學過的重複,還會更加有趣:

glsl 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; }

https://code.juejin.cn/pen/7108670645424095239

這一節主要以演示效果為主,理論很簡單,就只是把直角座標轉換為極座標,但是我們發現這種簡單的座標轉換,會衍生出很有趣的圖形。

你可以把前面的這些例子中的程式碼引數修改一下,多嘗試幾下,看看還會出現什麼效果。如果你發現了更有意思的效果,可以分享到評論區裡。