LoginSignup
6
8

More than 3 years have passed since last update.

Electron透過ウィンドウを作って画面に情報をだすサンプル

Posted at

なに?

Electron というHTML/JavaScriptでアプリを作れるフレームワークを使って、画面を演出してみます。

通常のパソコンのデスクトップの上に、electron で作った透明ウィンドウを重ねてそこに文字なり画像なりを出す仕組みです。

image.png

例えば、テレビのニュース番組みたいに天気予報を画面に出してみたり、ニコニコ動画風に画面にコメント流してみたり、ニュース速報出してみたり。そんなことが可能になります。

サンプル

難しい説明はぬきにしてサンプルです。

以下のファイルを準備します。

  test/
    index.js
    index.html
    style.css
index.js
"use strct";

const electron = require("electron");
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

let mainWindow = null;

app.on("window-all-closed", () => {
  if (process.platform != "darwin") {
    app.quit();
  }
});

app.on("ready", () => {
  mainWindow = new BrowserWindow({
    left: 0,
    top:0,
    frame: false,
    show: true,
    transparent: true,
    alwaysOnTop: true
    });

  mainWindow.setIgnoreMouseEvents(true);
  mainWindow.maximize();
  mainWindow.loadURL(`file://${__dirname}/index.html`);
  mainWindow.on("closed", () => {
    mainWindow = null;
  });
});
index.html
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="./style.css">
    <title>electron</title>
</head>

<body>
    <div id='sampleBox'>
        <p class='heart'>💛</p>
    </div>
</body>

<script type="text/javascript">
    window.onload = function () {
        autoHeart();
    }

    function autoHeart() {
        windowHeight = window.innerHeight;
        windowWidth = window.innerWidth;
        setInterval(() => {
            var sampleHearts = document.getElementsByClassName("heart");
            for(let i=0; sampleHearts.length; i++){
                sampleHearts[i].style.left = (Math.random() * windowWidth) + "px"
                sampleHearts[i].style.top = (Math.random() * windowHeight) + "px"
            }
        }, 1000)
    }
</script>

</html>
style.css
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html {
    height: 100%;
    width: 100%
}

body {
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.0);
}

canvas {
    height: 100%;
    width: 100%;
}

#sampleBox {
    width: 100%;
    height: 100%;
    position: relative;
    font-size: 100px;
}

.heart {
    position: absolute;
}

実行は簡単で、まず electron をインストールしておきます。

npm install -g electron

そして今回作ったファイルの場所で実行します。

electron .

これで画面上にハートが ぱっ ぱっ が出てきたと思います。

次にやること

今回わかりやすくするため極力簡単なコードにおさめました。

そもそも electron がそうなのですが、サンプルコードを見ていただければわかりますが比較的シンプルに単なるHTMLとJavaScriptで出来ています。

あとは定期的にAPIをたたいてニュースを取得して画面にだす。 Twitter APIをたたいて何かだす。 天気予報をだす。 そんなことも比較的簡単にできますのでみなさんぜひ色々遊んでみてください!!

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8