WebGL着色器简介

How does Dropbox make that effect where it looks like I am painting a McLaren as I drag my mouse over it?

Dropbox 是如何实现那种效果的?当我拖动鼠标时,看起来就像在为一辆 McLaren 喷漆。

They are using WebGL with no libraries or frameworks, just raw hand coded WebGL shaders.

他们使用的是 WebGL,没有依赖任何库或框架,只是手写的原生 WebGL 着色器。

A lot of people hear WebGL and think 3D and heavy with big slow libraries, but it does not have to be that way.

很多人一听到 WebGL 就想到 3D 和庞大的慢速库,但其实不必如此。

WebGL shaders use a small specialized language that can seem scary at first, but they are not.

WebGL shaders 使用一种小巧的专用语言,乍看可能吓人,其实并不可怕。

WebGL itself isn’t slow. Using large complex models like this can be.

WebGL 本身并不慢。使用像这样庞大复杂的模型才会慢。

Let’s learn the basics so you can make cool stuff by hand or with AI like I did in Builder.io, then use it for effects like this.

让我们先学点基础,这样你就能亲手或用 AI 做出酷炫的东西,就像我在 Builder.io 里做的那样,然后把它用在像这样的效果上。

 What's really cool about WebGL is it gives you per pixel precision. Fragment shaders run super fast concurrently on your GPU per pixel.

 WebGL 真正酷的地方在于它能提供逐像素的精度。片段着色器会在 GPU 上为每个像素并行高速运行。

image.png

This gives us a level of per-pixel control we can’t do any other way on the web, to let us do all kinds of cool things:

这让我们获得了在 web 上其他方式无法实现的逐像素控制级别,从而能做各种酷炫的事情:

Playing with WebGL effects through prompting in Builder.io.

Builder.io 中通过提示玩转 WebGL 效果。

A fragment shader runs once per pixel and returns the color for that pixel. The absolute smallest version just hard codes a color. That is it.

片段着色器对每个像素运行一次,返回该像素的颜色。最简版本就是直接硬编码一个颜色,仅此而已。

precision mediump float;
void main() {
 gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); // solid green
}

Change the numbers to make it blue or red. You now have a working shader.

修改数字即可让它变成蓝色或红色。你现在拥有了一个可用的着色器。

We have two images: one is the outline or unpainted car, the other is the painted version.

我们有两张图:一张是线稿或未喷漆的车,另一张是已喷漆的版本。

image.png

The fragment shader chooses per pixel which one to show. Near the cursor we reveal paint, away from the cursor we show the outline. That is the entire trick.

片段着色器逐像素决定显示哪一张图。靠近光标的地方显示喷漆,远离光标的地方显示线稿。就这么简单。

To do that we pass a f...

开通本站会员,查看完整译文。

Главная - Вики-сайт
Copyright © 2011-2025 iteam. Current version is 2.146.0. UTC+08:00, 2025-10-23 07:15
浙ICP备14020137号-1 $Гость$