无法在Electron(javascript)中制作透明窗口

时间:2018-11-29 11:39:34

标签: electron

我试图用ElectronJs制作透明窗口,但是我得到了黑色背景。

我在Linux(Debian Jessie)上

我尝试了不同的版本:最新版本,测试版和每夜版本,结果相同。

我有适用于同一台机器的NW.js版本,所以我希望这是电子问题。

这是我的main.js代码:

const {app, BrowserWindow} = require('electron');
let mainWindow;
function createWindow () {
  mainWindow = new BrowserWindow({width: 920, height: 300,  frame:true, transparent:true, backgroundColor: '#00FFFFFF'});
  mainWindow.loadFile('index.html');
  mainWindow.on('closed', function () {
    mainWindow = null;
  });
}
app.on('ready', createWindow);

这是我的index.html代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body style="background-color:rgba(255,255,255,0); color:lightgrey;">
    <h1>Hello World!</h1>
    <!-- All of the Node.js APIs are available in this renderer process. -->
    We are using Node.js <script>document.write(process.versions.node)</script>,
    Chromium <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.

    <script>
      // You can also require other files to run in this process
      // require('./renderer.js')
    </script>
  </body>
</html>

问题在于背景不是透明的而是黑色的:

enter image description here

尝试过不同的尝试而没有成功(例如app.disableHardwareAcceleration()

有人知道解决方案或完整的示例吗?

Thx

-

编辑1: 也尝试过有无--enable-transparent-visuals --disable-gpuhere

4 个答案:

答案 0 :(得分:2)

这是Electron项目中一个非常古老的回归错误。

请参见https://github.com/electron/electron/issues/15947

要绕过该问题,只需将其降级为最新的工作版本 1.4.16 2.0.16


编辑1:如果在就绪事件后等待至少300毫秒打开窗口,它将正常工作

app.on('ready', () => setTimeout(onAppReady, 300));

而且您在package.json中不需要--disable-gpu选项

"start": "electron --enable-transparent-visuals ."

编辑2: 要立即使用它,请使用以下仓库:https://gitlab.com/doom-fr/electron-transparency-demo

git clone https://gitlab.com/doom-fr/electron-transparency-demo
cd electron-transparency-demo
npm install
npm start
# or npm run startWithTransparentOption
# or npm run startWithAllOptions

对我来说,与npm startnpm run startWithTransparentOption一起使用

答案 1 :(得分:1)

我找到了使它工作的方法!尝试在Electron准备好10毫秒后创建窗口,如下所示:

app.on('ready', function () {
    setTimeout(function() {
        createWindow();
    }, 10);
});

而不是:app.on('ready', createWindow);

我是从以下Github帖子中找到的:https://github.com/electron/electron/issues/2170#issuecomment-361549395

此外,您需要保留以下命令行标志才能使其正常工作:--enable-transparent-visuals --disable-gpu


很遗憾,Electron在Linux上不支持透明窗口。

我实际上已经尝试了很多方法来使其正常工作,但仍然没有任何效果。

来源:https://github.com/electron/electron/issues/8532#issuecomment-306383343

答案 2 :(得分:1)

如果有人在新版本中遇到此错误,则您已禁用或取消了开发者工具的连接,那么您将能够使用透明窗口成功

win.webContents.openDevTools({mode:'undocked'})

答案 3 :(得分:0)

BrowserWindow {transparent:true}在您不打开devTools即不添加的情况下有效

YourNewBrowserWindow.webContents.openDevTools()到main.js(或electron.js)脚本