Tauri 透明窗口与鼠标穿透

2,265 阅读1分钟

这是个简单的创建 Tuari 透明窗口的教程,你可以在 GitHub 上找到示例代码。

1. 去除边框和标题栏

Tauri 默认窗口是带有边框和标题栏的,你可以通过在配置文件 tauri.conf.json 中添加 "decorations": false 去除边框和标题栏。

{
  "tauri": {
    "windows": [
      {
        "decorations": false
      }
    ]
  }
}

去除边框和标题栏之前:

image.png

之后:

image.png

2. 使窗口透明

同样,你只需要在配置文件 tauri.conf.json 中添加 "transparent": true 即可使窗口透明。如果你使用的是 MacOS,可能需要额外的设置,详情请看 Tauri 的官方文档

{
  "tauri": {
    "windows": [
      {
        "transparent": true
      }
    ]
  }
}

3. 使 Webview 透明

配置 transparenttrue 之后窗口是透明了,但是 Webview 仍非透明,你可以设置通过 css 或者元素的 style 属性使其透明,比如:

html, body {
  background-color: transparent;
}

如果你的窗口还不是透明的,可以检查下是否有其他的 css 覆盖 background-color: transparent;,或者检查 body 内是否存在不透明的元素。

最终效果:

image.png

注意

窗口拖动

在第一步中我们去除了标题栏,因而没法拖动窗口。最简单的解决方法就是:

  1. 在配置文件中添加 "startDragging": true(请注意配置插入的位置)。
{
  "tauri": {
    "allowlist": {
      "window": {
        "startDragging": true
      }
    },
  }
}
  1. 在你想拖动的元素双添加属性 data-tauri-drag-region。例如你可以通过如下 div 拖动窗口。
<div data-tauri-drag-region>Only this element can drag the window</div>

鼠标穿透

如果你使用鼠标穿透,可以使用在前端使用 API setIgnoreCursorEvents

import { appWindow } from '@tauri-apps/api/window';
await appWindow.setIgnoreCursorEvents(true);

也可以在 Rust 中使用。

tauri::Builder::default()
  .setup(|app| {
      let window = app.get_window("main").unwrap();
      window.set_ignore_cursor_events(true)
              .expect("error setting ignore cursor events");
      Ok(())
  })