Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

为 Web 导出

参见

这个页面描述的是如何将 Godot 项目导出到 HTML。如果你想要找的是从源码编译编辑器或导出模板二进制文件,请阅读 为 Web 平台编译

HTML5 export allows publishing games made in Godot Engine to the browser. This requires support for WebAssembly, WebGL and SharedArrayBuffer in the user's browser.

注意

Projects written in C# using Godot 4 currently cannot be exported to the web. To use C# on web platforms, use Godot 3 instead.

小技巧

Use the browser-integrated developer console, usually opened with F12 (Cmd + Option + I on macOS), to view debug information like JavaScript, engine, and WebGL errors.

注意

Godot 4's HTML5 exports currently cannot run on macOS and iOS due to upstream bugs with SharedArrayBuffer and WebGL 2.0. We recommend using macOS and iOS native export functionality instead, as it will also result in better performance.

Godot 3's HTML5 exports are more compatible with various browsers in general, especially when using the GLES2 rendering backend (which only requires WebGL 1.0).

WebGL 版本

Godot 4.0 and later can only target WebGL 2.0 (using the Compatibility rendering method). There is no stable way to run Vulkan applications on the web yet.

See Can I use WebGL 2.0 for a list of browser versions supporting WebGL 2.0. Note that Safari has several issues with WebGL 2.0 support that other browsers don't have, so we recommend using a Chromium-based browser or Firefox if possible.

导出选项

如果可以使用可运行的Web导出模板, 则编辑器中的 停止场景播放编辑的场景 按钮之间会出现一个按钮, 可以在默认浏览器中快速打开游戏进行测试.

If you plan to use VRAM compression make sure that Vram Texture Compression is enabled for the targeted platforms (enabling both For Desktop and For Mobile will result in a bigger, but more compatible export).

如果给出了 自定义HTML Shell 文件的路径, 则将使用它来代替默认的HTML页面. 请参阅 导出自定义 HTML 页面.

Head Include 被附加到生成的HTML页面的 <head> 元素中. 例如, 这允许加载webfonts和第三方JavaScript APIs, 包括CSS或运行JavaScript代码.

重要

每个项目必须生成他们自己的HTML文件。在导出时,几个文本占位符会在生成的HTML文件中被替换,专门用于给定的导出选项。任何对该HTML文件的直接修改都会在以后的导出中丢失。要自定义生成的文件,请使用** 自定义HTML shell**选 项。

限制

出于安全和隐私的原因, 许多在本机平台上轻松工作的功能在Web平台上更加复杂. 以下列出了将Godot游戏移植到Web时应注意的限制.

重要

浏览器供应商正在使越来越多的功能只在 安全上下文 中可用,这意味着这些功能只有在通过安全的HTTPS连接提供网页时才可用(localhost通常不受这种要求影响)。

使用 cookie 进行数据持久化

如果需要持久化 user:// 文件系统, 用户必须 允许cookie (特别是IndexedDB). 当玩 iframe 中呈现的游戏时, 还必须启用 第三方 cookie. 隐身/隐私浏览模式也会防止持久性.

方法 OS.is_userfs_persistent() 可用于检查 user:// 文件系统是否持久, 但在某些情况下会误报.

后台处理

这个标签页不再是用户浏览器的活动标签页时,项目就会被浏览器暂停。也就是说不会运行 _process()_physics_process() 等函数,除非用户重新激活了这个标签页(切换到这个标签页)。如果用户在标签页外停留了过长的时间,就可能造成网络游戏的掉线。

这一限制不适用于丢失焦点的浏览器窗口。因此,对于用户而言,变通方法是让项目运行在一个单独的窗口中,而不是标签页。

全屏和鼠标捕获

浏览器不允许任意 进入全屏 . ** 捕获光标** 也是如此. 相反, 这些操作必须作为对JavaScript输入事件的响应而发生. 在Godot中, 这意味着从按下的输入事件, 例如 _input_unhandled_input, 回调中进入全屏. 查询 Input 单例是不够的, 相关的输入事件当前必须是活动的.

出于同样的原因, 除非从有效的输入事件处理程序中启动引擎, 否则全屏项目设置将不起作用. 这需要 定制HTML 页面.

音频

Some browsers restrict autoplay for audio on websites. The easiest way around this limitation is to request the player to click, tap or press a key/button to enable audio, for instance when displaying a splash screen at the start of your game.

参见

Google提供了有关其 网络音频自动播放政策 的其他信息.

Apple's Safari team also posted additional information about their Auto-Play Policy Changes for macOS.

警告

访问麦克风需要安全上下文

网络

由于缺乏浏览器的支持,低级别的网络没有实现。

目前,只有 HTTP client, HTTP requests, WebSocket (client)WebRTC 被支持。

HTTP类在HTML5平台上也有若干限制:

  • 无法访问或更改 StreamPeer

  • Threaded/Blocking 模式不可用

  • 每帧不能进行多次, 因此循环中的轮询将冻结

  • 没有分块响应

  • 无法禁用主机验证

  • 遵循 同源政策

剪贴板

在引擎和操作系统之间同步剪贴板需要浏览器 剪贴板 API ,此外,由于该 API 的异步性,从 GDScript 访问时可能不可靠。

警告

需要安全上下文

游戏手柄

按下游戏手柄上面的任一按钮之后,这个游戏手柄才能被检测到。根据浏览器、操作系统、游戏手柄三者的组合不同,游戏手柄的映射可能有误,可惜由于隐私方面的考虑, 游戏手柄 API 并没有提供可靠的方法来检测游戏手柄的信息,因而无法根据模型、供应商、操作系统来进行重新映射。

警告

需要安全上下文

启动画面不显示

默认的 HTML 页面在加载时不显示启动画面。然而,该图像会被导出为 PNG 文件,因此可以通过 自定义 HTML 页面 来显示。

提供文件

导出为Web生成多个要从Web服务器提供的文件, 包括用于演示的默认HTML页面. 可以使用自定义HTML文件, 请参阅 导出自定义 HTML 页面 .

警告

To ensure low audio latency and the ability to use Thread in web exports, Godot 4 web exports always use SharedArrayBuffer. This requires a secure context, while also requiring the following CORS headers to be set when serving the files:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

如果 Web 服务器不是你的,或者你无法添加响应报头,请使用 coi-serviceworker 作为变通方案。

客户端收不到必要的响应报头,项目就不会运行

生成的 .html 文件可以在 Apache 服务器中用作 DirectoryIndex,文件名可以随便修改,比如可以改成 index.html。默认情况下不会用到这个名称。

The HTML page draws the game at maximum size within the browser window. This way, it can be inserted into an <iframe> with the game's size, as is common on most web game hosting sites.

其他导出的文件在 .html 文件旁边, 按原样提供, 名称不变. .wasm 文件是实现引擎的二进制WebAssembly模块. .pck 文件是包含你的游戏的Godot主包. .js 文件包含启动代码, .html 文件使用它来访问引擎. .png 文件包含启动画面图像. 默认HTML页面中未使用它, 但 自定义HTML 页面 中包含了它.

.pck 文件是二进制文件, 通常与MIME类型 application/octet-stream 一起分发. .wasm 文件以 application/wasm 分发.

警告

分发WebAssembly模块(.wasm)时, 使用一个 application/wasm 以外的MIME类型, 可能会阻止某些启动优化.

建议使用服务器端压缩来分发文件,特别是 .pck.wasm 文件,因为这种文件通常很大。WebAssembly 模块的压缩做得特别好,使用 gzip 压缩最多能够缩小到原始大小的四分之一左右。如果 Web 服务器支持的话,请考虑使用 Brotli 预压缩,能够进一步节省文件大小。

提供即时压缩的主机: GitHub Pages (gzip)

不提供即时压缩的主机: itch.io, GitLab 页面 ( 支持手动gzip预压缩 )

小技巧

Godot 的仓库中包含了一个用来运行本地 Web 服务器的 Python 脚本。这个脚本原本是用于测试 Web 编辑器的,但也可以用来测试导出后的项目。

将链接中的文件保存为 serve.py 文件,将这个文件移动到包含导出后项目的 index.html 的文件夹中,然后在该文件夹中打开命令提示符,执行以下命令:

# You may need to replace `python` with `python3` on some platforms.
python serve.py --root .

On Windows, you can open a command prompt in the current folder by holding Shift and right-clicking on empty space in Windows Explorer, then choosing Open PowerShell window here.

This will serve the contents of the current folder and open the default web browser automatically.

Note that for production use cases, this Python-based web server should not be used. Instead, you should use an established web server such as Apache or nginx.

从脚本调用 JavaScript

In web builds, the JavaScriptBridge singleton is implemented. It offers a single method called eval that works similarly to the JavaScript function of the same name. It takes a string as an argument and executes it as JavaScript code. This allows interacting with the browser in ways not possible with script languages integrated into Godot.

func my_func():
    JavaScriptBridge.eval("alert('Calling JavaScript per GDScript!');")

最后一个JavaScript语句的值转换为GDScript值, 并在某些情况下由 eval() 返回:

  • JavaScript number is returned as float

  • JavaScript boolean is returned as bool

  • JavaScript string is returned as String

  • JavaScript ArrayBuffer, TypedArray and DataView are returned as PackedByteArray

func my_func2():
    var js_return = JavaScriptBridge.eval("var myNumber = 1; myNumber + 2;")
    print(js_return) # prints '3.0'

任何其他JavaScript值都返回为 null .

HTML5 export templates may be built without support for the singleton to improve security. With such templates, and on platforms other than HTML5, calling JavaScriptBridge.eval will also return null. The availability of the singleton can be checked with the web feature tag:

func my_func3():
    if OS.has_feature('web'):
        JavaScriptBridge.eval("""
            console.log('The JavaScriptBridge singleton is available')
        """)
    else:
        print("The JavaScriptBridge singleton is NOT available")

小技巧

GDScript中的多行字符串由3双引号 """ 包围, 如同上文中的 my_func3() 那样, 有助于保证JavaScript代码的可读性.

The eval method also accepts a second, optional Boolean argument, which specifies whether to execute the code in the global execution context, defaulting to false to prevent polluting the global namespace:

func my_func4():
    # execute in global execution context,
    # thus adding a new JavaScript global variable `SomeGlobal`
    JavaScriptBridge.eval("var SomeGlobal = {};", true)

环境变量

你可以使用以下环境变量在编辑器外部设置导出选项。在导出过程中,这些值会覆盖你在导出菜单中设置的值。

HTML5 导出环境变量

导出选项

环境变量

加密 / 密钥

GODOT_SCRIPT_ENCRYPTION_KEY