Skip to content

Instantly share code, notes, and snippets.

@jrieken
Last active Dec 28, 2018
Embed
What would you like to do?
Electron Fiddle - Rabbits
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Rabbit!</title>
</head>
<body style="height: 800px; width: 1000px;">
<span class="rabbit" style="position:absolute; font-size: 45px;">🐇</span>
<script>
// the rabbit-span element
const rabbit = document.querySelector('.rabbit');
// drag rabbit around when mouse moves
document.body.addEventListener('mousemove', e => {
rabbit.style.left = `${e.clientX - 10}px`;
rabbit.style.top = `${e.clientY + 10}px`;
});
// add more rabbit and compute fibonacci number
// in the main process when mouse is down
const { ipcRenderer } = require('electron');
let month = 0;
document.body.addEventListener('mousedown', e => {
// add a rabbit-clone
const newRabbit = rabbit.cloneNode(true);
document.body.appendChild(newRabbit);
// fib of number of rabbit (speed up with meta key)
if(e.metaKey) {
month *= 2;
} else {
month += 1;
}
const n = month;
// send request and update rabbit with response
ipcRenderer.send('req/fib', n);
ipcRenderer.once('res/fib', (event, arg) => {
newRabbit.innerHTML += `<span style="font-size: 23px;">fib(${n}) = ${arg}</span>`;
setTimeout(() => { newRabbit.style.opacity = '.5';}, 300);
});
});
</script>
</body>
</html>
const { app, ipcMain, BrowserWindow } = require('electron')
let mainWindow
function fib(n) {
if (n <= 1) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}
function createWindow() {
mainWindow = new BrowserWindow({ width: 1000, height: 800 })
mainWindow.loadFile('index.html')
// request/response: fibonacci numbers
ipcMain.on('req/fib', (event, arg) => {
const n = fib(arg);
event.sender.send('res/fib', n)
});
mainWindow.on('closed', function () {
mainWindow = null
});
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment