javascript 如何使用 html5 画布扭曲图像以创建在风中挥舞的旗帜效果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4362248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:10:41  来源:igfitidea点击:

How to distort an image to create flag waving in the wind effect using html5 canvas

javascriptcsshtmlanimationcanvas

提问by Andres

Given an image, I need to create an animation of the image being distorted as though it's a flag waving in the wind, using javascript and an html5 canvas.

给定一个图像,我需要使用 javascript 和 html5 画布创建一个图像扭曲的动画,就好像它是一面在风中飘扬的旗帜。

Bonus: I also would like to be able to export this animation as a png.

奖励:我也希望能够将此动画导出为 png。

回答by Phrogz

I've created a simple exampleof a flag waving in the wind. It's ugly because I draw the flag to fill the canvas (instead of leaving padding for the flag to wave into) and because I don't make any attempt at anti-aliasing. I also didn't make any attempt to provide 3D shading, which would help the effect.

我已经创建了一个简单的例子,旗帜在风中飘扬。这很丑陋,因为我绘制标志以填充画布(而不是留下填充以让标志挥动)并且因为我没有尝试抗锯齿。我也没有尝试提供 3D 着色,这将有助于效果。

I can get 64fps with a 320px wide flag in Chrome v8 on my machine. If you want to test the speed yourself, change the fps on line 59 to 1000and uncomment lines 63 and 82; it will then output fps information every 100 frames to the console.

我可以在我的机器上的 Chrome v8 中使用 320px 宽的标志获得 64fps。如果你想自己测试速度,将第59行的fps更改为1000并取消第63和82行的注释;然后它将每 100 帧向控制台输出 fps 信息。

This won't work in IE8-, even with ExCanvas, because there is no mechanism to access individual pixel data there.

这在 IE8- 中不起作用,即使使用ExCanvas也是如此,因为那里没有访问单个像素数据的机制。

Edit: Just for fun, I've updated the sample to shade the ripples as they go through the image.

编辑:只是为了好玩,我更新了示例以在波纹穿过图像时对其进行着色。

Edit2: For more fun, I added padding to the flag drawing (no more clipping) and I added a 'squeeze' factor that lets you make the right side of the flag bigger or smaller than the original (for perspective). Since it slows down the performance a little I've uploaded it as a separate sample.

Edit2:为了更有趣,我在标志绘图中添加了填充(不再剪裁),并且我添加了一个“挤压”因子,使您可以使标志的右侧比原来更大或更小(用于透视)。由于它稍微降低了性能,我将它作为单独的示例上传。

                      US Flag waving in the wind (static screenshot)

                      美国国旗迎风飘扬(静态截图)