Building Electron Applications with Multiple Pages

If you don’t want to dive into webpack/framework build frame, but need an easy way to use multiple pages in electron with simple navigation, this might work for you.

There are a few approaches to handling multiple pages in an electron app. Since chromium comes bundled with electron, essentially a web browser, and electron runs a node application, one approach is just to serve multiple pages as external html files. The same way you might on a web server. You can load these external pages, locally or remotely, into the current BrowserWindow via links or api calls. But results aren’t as seamless as an application. There’s a notorious screen flash that happens sometimes when the external page loads. Though mitigated somewhat with tweaks, electron is really designed for single page/cached content applications.

Multiple pages can be implemented through views, available in various frameworks with architectures for routing and templating, like Vue, React and Angular. These assemble pages by building custom objects loaded into memory. But if we don’t want to use a framework with their attendant complexities, and don’t want janky window flashing from hard links, there’s a third alternative.

Deep in the source for lies a useful approach. I decided to simplify, deconstruct and generalize it here. I’ll also integrate Bootstrap 4 to leverage its tab components to do the actual navigation. Because, lazy.

To build from scratch:

1. git clone
2. cd electron-quick-start
3. npm install bootstrap
4. npm install jquery
5. npm install popper.js
6. npm install

Now, in the head of index.html add:

<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">

In the script section of the same index.html add:

window.$ = window.jquery = require("jquery");
window.popper = require("popper.js");

Now the electron app is fully wired for bootstrap. Next we’ll create external templates for each of our pages. Here’s an example of a template for the main page created in an external file called main.html:

<div class="container template" id="main-template" data-tab="main">
<!-- all the stuff for the main page goes here... -->

Create one of these files for each page in the application. Ensure that each has its own unique id and data-tab value. Next let’s go back and tweak the index.html to reference the templates. In the head section of the html:

<link rel="import" href="main.html">
<link rel="import" href="settings.html">
<link rel="import" href="help.html">
<link rel="import" href="contact.html">

for as many template pages as we created.

Next add the following to the script block in the same index.html file:

const links = document.querySelectorAll('link[rel="import"]');
links.forEach((link) => {
    let template = link.import.querySelector('template');
    let clone = document.importNode(template.content, true);
    let target = clone.querySelector(".template");

What this script fragment does is look for every import link in the head section, which it then loads and caches in memory as a document fragment and appends to an html element in the dom with an id that matches the id referenced by the data-tab in the template. Templates are a very cool, seldom utilized, feature baked into HTML5.

So all that’s left is replacing the body of index.html with the following to provide navigation and some slots and scaffolding for the pages.

<div class="container my-4"><div class="row"><div class="col-2">
<div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">

<a class="nav-link active" id="home-tab" data-toggle="pill" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
<a class="nav-link" id="about-tab" data-toggle="pill" href="#about" role="tab" aria-controls="about" aria-selected="false">About</a>
<a class="nav-link" id="contact-tab" data-toggle="pill" href="#contact" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
<a class="nav-link" id="settings-tab" data-toggle="pill" href="#settings" role="tab" aria-controls="settings" aria-selected="false">Settings</a>


<div class="col-10"><div class="tab-content" id="v-pills-tabContent">

<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab"></div>
<div class="tab-pane fade" id="about" role="tabpanel" aria-labelledby="about-tab"></div>
<div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab"></div>
<div class="tab-pane fade" id="settings" role="tabpanel" aria-labelledby="settings-tab"></div>


Now run:

npm start

and voila. A multipage electron application using HTML5 templates and bootstrap for easy styling and navigation.

Complete source code available on

(For a quickstart on electron in general, along with a solid discussion of options for packaging, updating and software certificates, I found this concise resource very well put together:


Equations of Form

Some people like zoos or art exhibits, I like to explore abstract species of thought. Yesterday I spent the afternoon roaming around L-systems.

L-systems are little self-contained universes of alphabets, axioms, and rules. The alphabets are building blocks and may be any symbols or letters imaginable. The axiom is an initial combination of those letters and the rules change the axiom, morphing it into something else generation by generation. This simple trifecta creates an infinity of forms.

L-systems are deterministic and linear. This means given a certain starting point and a certain set of rules, they will always produce the same results. They don’t have the ability of chaotic systems to veer off in unexpected directions, although there may be ways of coaxing them to do so depending on how their results are interpreted. Part of their algorithmic DNA is recursion. A fractal reflexiveness that applies rules to the results of rules in an infinite spiral.

We can map L-systems graphically and they can produce intricate patterns with an affinity to the natural world: leaves, trees, clouds, terrain. But they don’t have to be interpreted graphically. They could be mapped to poetry, music, rhythm, dance.

Here’s the relevant Processing code that interpreted the L-system for the graphic above:

// Symbols: F+-[]
// Axiom: F
// Rules F->FF+[+F-F-F]-[-F+F+F]

var axiom = "F";
var sentence = axiom;
var rules = [];


// This is the entire l-system processor
function generate() {
	var newSentence = "";
	for (var i = 0; i < sentence.length; i++) {
		var ch = sentence.charAt(i);
		var nl = newSentence.length;
		for (var j = 0; j < rules.length; j++) {
			// look for one rune that matches this symbol, apply it and bail
  			if (ch == rules[j].l) { 
  				newSentence += rules[j].r;
		// if no rules matched, return symbol unchanged
		if (nl === newSentence.length) newSentence += ch; 
	sentence = newSentence;

// Interpret l-system generated string using old logo method
// if moving a turtle around to draw lines
var len = 60
var angle = 20

function interpret() {
	len *= 0.5;
	translate(width/2, height);
	for (var i = 0; i < sentence.length; i++) {
		var ch = sentence.charAt(i);
		if (ch == "F") {
			translate(0, -len);
		} else if (ch == "+") {
		} else if (ch == "-") {
		} else if (ch == "[") {
		} else if (ch == "]") {

Inspiration for this came from Dan’s. always entertaining and educational, Coding Challenges; an even deeper dive can be found here.

The Art of Particles

Particle systems first appeared in 1982. A special effect artist, Bill Reeves, used them in Star Trek II: The Wrath of Kahn for a scene called the “genesis effect.”

In essence a particle system is just an algorithm controlling particle creation and interaction. In practice this normally consists of an emitter, usually invisible, positioned somewhere in the world and tiny graphic elements (particles) the emitter spits out from its hidden position, all at once or in intervals.

By varying how, when and where of particle creation and what forces act upon them, we can simulate a variety of real-world effects like fire, smoke and rain. In theory any physical phenomenon could be simulated by a particle system since all matter is basically made up of particles (atoms.) However, the computational cost of juggling even a few thousand particles rapidly becomes a bottleneck. But with a modest number of particles, and clever coding, one can still produce cool effects, even in a lowly web browser.

For code geeks, particle systems are great projects to make from scratch, but this post is focused on their use in generative art. We will leverage Phaser, an engine used to create HTML5 games, primarily because it comes with a built in particle system and physics engine (useful for applying forces to the particles, like gravity and acceleration.) You could also experiment with these systems in Processing and Daniel Shiffman has some great tutorials on a simple prototype.

Here’s a self-contained Phaser scaffold to kick off experiments:

<!DOCTYPE html>
<meta charset='UTF-8'>
<meta name='viewport' content='initial-scale=1 maximum-scale=1 user-scalable=0'> 
<title>Phaser Scaffold</title>
 body {
 background-color: #000000;
 border: 0;
 margin: 0; 
 overflow: hidden:
<script src=''></script>
<script type="text/javascript">
var game = new Phaser.Game('100%', '100%', 
 Phaser.AUTO, 'scratchpad', 
 {preload:preload, create:create}

function preload() {

function create() {


Phaser looks for function names to call at specific times. The function preload() is called for loading images and assets, create() is then called after all assets are loaded. After that, if update() and render() are defined, they are called in the standard game loop pattern at the maximum browser framerate.

Creating particles with this scaffold is easy. We’ll just load a small image to serve as the particle and define an emitter with some parameters to shoot copies onto the scene:

var emitter;
var maxParticles = 1000;
var explode=false;
var lifespan=5000;
var frequency=5;
var quantity=0;    // if 0 and explode false then continuous

function preload() {
  game.load.image('particle', 'p1.png');

function create() {
  emitter = game.add.emitter(,, maxParticles);  
  emitter.start(explode, lifespan, frequency, quantity);

Particles will either explode from the emitter all at once, like a firework, in which case:

  • explode = true
  • lifespan = how long the particles “live” in milliseconds, after which they dissappear from screen
  • frequency has no effect if explode = true
  • quantity is how many particles are created during the explosion, up to amount in maxParticles

For stream from the emitter in a continuous flow of particles:

  • explode = false
  • frequency = interval in milliseconds between firing particles
  • quantity = 0 means keep firing particles indefinitely at the frequency specified, if maxParticles are reached, wait until one dies before firing another to take its place; if quantity = n just fire n particles total and then stop

Emitters have many additional properties to tweak besides what’s set in the start parameter. For example:

  • minParticleScale, maxParticleScale sets the range between the particle is randomly scaled when created
  • setAlpha(0.1, 0.9); as an example, sets the range of the transparency applied to the particle
  • width and height set the the area in which particles emerge, by default this is a single point, like a cannon, but it can be expanded to any size and the particle will emerge from a random location within this area
  • minParticleSpeed, maxParticleSpeed control a range of velocities each particle is assigned

Here’s a quick technique for masking images in Phaser:

  var mask =, 0);
  mask.drawCircle(,, 645);

Which creates a mask that be applied to any image, essentially “clipping” what’s displayed of the image to just the size and shape of the mask. That’s all the elements needed to create the following project:

See the Pen There’s Bugs in My Code by Kentskyo (@kentskyo) on CodePen.0

Canvas – Animation

Outside of the canvas api but part of HTML5, the widely supported requestAnimationFrame method replaces the old setInterval() and setTimeout() functions of the past for browser animation. A basic setup is as follows:

var start, elapsed, fps;

function animate(timestamp) {
    if (!start) start = timestamp; // first time
    elapsed = timestamp - start;
    start = timestamp;             // reset baseline
    fps = 1000 / elapsed;


The animate function fires at whatever the browser determines is an optimal framerate, generally 60 times a second. If a browser tab running animate code is not visible, it may not be called at all (chrome), or may be called once a second (firefox); the actual behavior of browsers in this situation is unspecified. A timestamp is passed as an argument to the callback routine set to a value from  at the time the callback was triggered.

With this timestamp value,  we can calculate effective frames per second and make adjustments to ensure animations run at a constant rate. Or we can use elapsed time to perform actions once a second or in intervals other than the framerate.

To move at a certain number of pixels per second, regardless of the framerate:

ball.vx * (elapsedTime / 1000);
ball.vy * (elapsedTime / 1000);

Where ball.vx and ball.vy = the number of pixels per second.

To finesse the timing of a sweeping second-hand, we can calculate the number of radians traversed per second by chopping a circle up into 60 segments: 2PI/60 and then increment the angle based on how much of the second has elapsed:

angle += 2PI/60 * (elapsed/1000);

To start the second-hand at a specific angle, like current seconds, it can be initialized like so:

angle = (Math.PI*2) * (new Date().getSeconds()/60) - Math.PI/2;

This adjusts for the fact that radian = 0 is actually at the 3 o’clock position of a circle, or 90 degrees.

Instead of hardcoding 60, any divisor from 0..n could be used to map the value n to its corresponding location on the circle.

The following experiment animates the second-hand as a line from the center to its time corrected position along the circumference each frame. This creates a smooth, sweeping movement. Another function plots the location of the current hour, displaying it as a translucent circle and displays the minutes numerically inside.

(Using text with canvas wasn’t covered yet, but is explained well here. Note also that two canvas elements are used and stacked one upon another using css. This allows the dial to be drawn once to improve performance, since it doesn’t change, and leverages the default transparency of a canvas.

See the Pen Clock by Kentskyo (@kentskyo) on CodePen.0