Monday, June 27, 2016

Game with Canvas and jspm

Last week I visited Joy of Coding in Rotterdam, NL. Some of the sessions were so-so, others were pretty good, like Emily Bache's Coding Dojo and Jack Franklin's talk on jspm. I started experimenting with jspm and decided to use it to make a small game.

Frictionless browser package management

You can use jspm to do a couple of things for you. It manages packages like jQuery, Babel, npm packages and more. It also loads modules from npm, github or from disk, but can also bundle your javascript and css for use in production. In this project I'll use it to load the game's classes and also have it transpile ES2015 code so that all browsers can run it.
Setting up a project with jspm is a 2 minute job. All you need to do is install jspm (node module) and run the jspm init to create a config file. You won't have to ever touch the config file if you want (but you can, of course!):

 npm init
 npm install jspm@beta --save-dev

You then run jspm init and it creates a config file for you:

node_modules/.bin/jspm init

Configuration file jspm.config.js does not exist, create it? [Yes]: Yes
Init mode (Quick, Standard, Custom) [Quick]: Quick
Local package name (recommended, optional): your_package
package.json directories.baseURL: .
package.json configFiles folder [./]: ./
Use package.json configFiles.jspm:dev? [No]: No
SystemJS.config browser baseURL (optional): /
SystemJS.config Node local project path [src/]: src/
SystemJS.config local package main [your_package.js]: your_package.js
SystemJS.config transpiler (Babel, Traceur, TypeScript, None) [babel]: babel

That's all! You can now start coding! In this case I'm telling it to import the bikebikebike package, which internally resolves to src/index.js. This index file then instantiates a new Game object and starts the game.

  <canvas id="canvas"></canvas>
  <script src="jspm_packages/system.js"></script>
  <script src="jspm.config.js"></script>
  <script type="text/javascript">

Game classes

The goal of this project was to set up a basic game framework which I can use to make an actual game. I wanted to have a player character on the screen and allow the user to move the character. In order to do this I created three classes: Game, Bike and Sprite. The Game class contains the main game loop, Bike is a bike with position, speed, colour and a Sprite. This last class is responsible for drawing sprites or spritesheets. Two utility classes handle user input and image loading. One thing I really like is the out-of-the-box babel ES2015 transpiling. Being able to use ES2015 syntax and import modules so easily is very nice and makes it fun to split up your code in multiple files and modules. 
Of course there are plenty of JavaScript packages and libraries that do this already, but jspm makes it so smooooooth!

While this was mainly a "Get to know jspm" project, it does define a game world (the entire screen!) and lets the user move their character around. With this framework all set up I'll focus on creating the actual game the next couple of weeks.

There's no playable codepen for this project, but you can browse and download the code on GitHub

Saturday, June 4, 2016

Canvas experiment 2: Simple particles

This is yet another Canvas experiment, just like the one last week. This time I'm experimenting with a couple of really basic particles:

ES2015: Classes and Extends

As you might've seen in the animation above, not all particles are the same. Some are square, some of those squares rotate and a couple of others are circles. I wanted to keep this relatively DRY, so started by writing a Particle class:

"use strict";
class Particle {
  constructor(x, y, width, height, lifetime, decayrate, color) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.color = color;

    this.lifetime = lifetime;
    this.INITIAL_LIFETIME = lifetime;
    this.decayrate = decayrate;

    this.xVel = 50 - Math.random() * 100;
    this.yVel = 50 + Math.random() * 50;

Every particle has an x and y position, a width, height and color. The lifetime and decayrate are also set by the user, but the x-velocity and y-velocity are just random numbers that feel good. Note the class keyword that was used to declare the Particle class. This keyword was added in ES2015 and is just syntactical sugar over the existing JavaScript objects and prototypes.

I like to move it

Particles that don't move are rather boring, so let's make them move their bodies.
First of all, we'll create the particle's update method. This function will be responsible for updating the particle's position and will also decrease its lifetime. At some point we'll want to destroy particles that have reached the end of their lifespan.

update(dTime) {
  this.lifetime -= this.decayrate * dTime;

  this.x += this.xVel * dTime;
  this.y += this.yVel * dTime;

The lifetime and xVel / yVel values are in seconds and pixels per seconds. This means that a particle with a lifetime of 5 will be on the screen for five seconds and one with an xVel of 100 would move to the right at a rate of 100 pixels per second.
They are then drawn to the screen, with an alpha value based on the remaining lifetime - particles will fade out slowly:

draw(context) {
  context.fillStyle = this.color;
  context.fillRect(this.x, this.y, this.width, this.height);
  context.globalAlpha = 1;

Draw and update whenever we can

Last week's experiment used setInterval to call the main draw function every 10ms.This experiment is a bit more demanding so I'm using Window.requestAnimationFrame to make sure everything keeps running just fine. This function takes a callback (draw) and passes it one argument, a high resolution timestamp. We'll use this in our update methods to keep our movement smooth. 

function draw(timestamp) {
  if(!prevTimestamp) { prevTimestamp = timestamp; }
  let dTime = (timestamp - prevTimestamp) / 1000;
  context.clearRect(0, 0, canvas.width, canvas.height);
  particles.forEach(function (particle) {
  prevTimestamp = timestamp;
  particles = particles.filter(filterExpiredParticles);

Give it a go!

The final thing is embedded below. I used some ES2015, which will only work if you use an up-to-date browser (IE users: 11 or Edge). You can view more on CodePen or browse the code on github.

Friday, May 27, 2016

Canvas experiment 1: OGD logo

Using the Canvas API you can easily draw shapes, text and other graphics on web pages, using only HTML and some JavaScript. The next couple of weeks I'll experiment with Canvas and publish a new blog post every weekend.

How does it work?

I created a couple of base HTML and CSS files so that I don't have to start from scratch every time I want to play with canvas. They're really basic and can be found right here on github.

The OGD logo contains six elements: the texts 'OGD', 'ict-diensten', 'samen slimmer', the red line and the two red shapes at the top left. Also, the entire thing is rotated about 20 degrees.

First I'm going to draw the text. This is easy enough using only two functions: context.font to set the font and context.fillText to draw the text. The colour is set using the fillStyle property.

function drawText() {
   context.fillStyle = '#6C276A';

   // OGD
   context.font = 'bold 164px ogd';
   context.fillText('OGD', OFFSET_X, OFFSET_Y);

   // ict-diensten
   context.font = 'bold 60px ogd';
   context.fillText('ict-diensten', OFFSET_X + 70, OFFSET_Y + 70);

   // samen slimmer
   context.font = 'italic normal 50px ogd';
   context.fillText('samen slimmer', OFFSET_X + 70, OFFSET_Y + 160);

Now that the text is drawn, I create the three other shapes using moveTo and lineTo. They are then drawn to the canvas using either fill or stroke.

// triangle left
context.moveTo(OFFSET_X - 160, OFFSET_Y - 100);
context.lineTo(OFFSET_X - 110, OFFSET_Y - 50);
context.lineTo(OFFSET_X - 160, OFFSET_Y);

// shape right
context.moveTo(OFFSET_X - 50, OFFSET_Y - 100);  // top right
context.lineTo(OFFSET_X - 50, OFFSET_Y);        // bottom right
context.lineTo(OFFSET_X - 125, OFFSET_Y);       // bottom left
context.lineTo(OFFSET_X - 75, OFFSET_Y - 50);   // center
context.lineTo(OFFSET_X - 125, OFFSET_Y - 100); // top left

// line
context.lineWidth = 3;
context.moveTo(OFFSET_X + 70, OFFSET_Y + 115);
context.lineTo(OFFSET_X + 380, OFFSET_Y + 115);

End result

The final thing is embedded below. Click the OGD logo to make it rotate. Click again to stop.
Note that I used some ES2015, which will only work if you use an up-to-date browser (IE users: 11 or Edge). You can view more on CodePen or browse the code on github.

Wednesday, May 25, 2016

Getting selected text in a Chrome extension

My Highlight to Chrome extension lets the user select any piece of code on a webpage and sends it to the API to retrieve code with syntax highlighting as HTML. It lets you easily generate nice looking code for use on blogs or web pages.

How does it work?

The latest version of the extension uses both a background script and a content script, as defined in its manifest.json. The original version however only required the main.js background script. The important bits are:

function contextMenuListener(info) {
  if(info.parentMenuItemId === 'tseidler_hilite_code') {
    var language = info.menuItemId.slice('tseidler_hilite_language_'.length);
    highlightSelection(info.selectionText, language);
  } else if(info.menuItemId === 'tseidler_hilite_code') {
    // if no language is given, highlightSelection will use the first language

function highlightSelection(selection, lexer) {
  // get settings from storage & do request{
    'highlight_output_style': 'colorful',
    'highlight_line_number':  true,
    'highlight_div_styles': 'none',
    'highlight_languages':  ['javascript']
  }, function (items) {
    var settings = {
      'lexer':      lexer || items.highlight_languages[0] || 'javascript',
      'style':      items.highlight_output_style,
      'linenos':    items.highlight_line_number,
      'divstyles':  items.highlight_div_styles

    doHilightAPIRequest(selection, settings, copyToClipBoard);
The contextMenuListener on line:1 handles the chrome.contextMenus.onClicked event - it is fired whenever a context menu item is clicked. It takes an info object which contains the key selectionText. This contains "The text for the context selection, if any." and so it seems like the ideal thing to use. That is how you get the user-selected text, according to the documentation. It works! Sort of...

What the documentation does not mention is that this property contains the selected text... as plain-text - it removes all whitespace from the code, rendering the generated HTML useless.

The workaround

Assuming I'm not the only one, nor the last one with this problem, I searched StackOverflow for a solution. Surely there has to be a way to get the selected text with spacing. And there is! That's what the content script is for.

Instead of using the info.selectedText to access the user's selection, the trick is to add an event listener that is fired on MouseUp. All it does is call window.getSelection() and send the result to our main script.

// workaround: Chrome's contextMenu's selectionText property strips whitespaces
document.addEventListener('mouseup', function () {
  var selection = window.getSelection().toString();
  if(selection.length > 0) {
        'type':       'selection',
        'selection':  selection

The main script receives the message, sets the internal selection variable and uses that to send the selected text to the API.

function messageListener(request) {
  if(request.type === 'rebuildContextMenus') {
  } else if(request.type === 'selection') {
    selectedText = request.selection;


Want to see all of the extension? Get the code on github, or download the extension in the Chrome web store.

Wednesday, April 13, 2016

Writing a Google Chrome extension

In the first short blurb I posted on this blog I spoke about the excellent service. Turns out they do not only have a pretty cool website, they also have an API that can be used by apps or other sites to create HTML from code! I've been wanting to create a Chrome extension for a while now and this just seemed like the perfect opportunity.

What should it do? 

The extension will be relatively simple. It'll let users select text(code!) in their browser. They can then right-click and choose to send the code to the API and copy the generated HTML and highlighted code to the clipboard. I want the user to be able to change the languages available for highlighting, enable and disable line numbers and change colour settings.

Where to start?

Not having written a Chrome extension before I had some reading to do. Fortunately Google have extensive documentation and extension samples to help you getting your very own Chrome extension up and running.

Turns out making a Chrome extension is not all that hard! All you really need is a manifest.json and a few lines of javascript. The manifest file tells Chrome what your extension is called, what the version number is, what the icons are and the permissions the extension requires. My manifest.json looks like this:

  "manifest_version": 2,

  "name": "Highlight to",
  "description": "This extension allows the user to highlight code to send to",
  "version": "0.1",
  "icons": {  },  
 "permissions": [

  "background": {
    "scripts": ["main.js"],
for the full file, have a look on github: /tseidler/extension-chrome-hightlight-code/manifest.json

It tells the browser to load a background script called main.js, which does all the work. Note that it requests five permissions:
  • clipboardWrite: to copy the generated HTML to the user's clipboard
  • contextMenus: so that we can respond when the user right-clicks the page
  • storage: to store user preferences
  • notifications: after sending the selected code to the API, inform the user of the result
  • we need this to be able to do requests to the API.
Next time I'll discuss the things I ran into trying to implement the above functionality. If you want to find them out for yourself, have a look at the code or the extension itself.

Monday, January 25, 2016

JavaScript Code Formatting in blogger

I'm trying to get formatted and highlighted code in Blogger. Looking on the web it seems one of the easier ways is to write code in your editor of choice and then use an online tool like to generate the HTML required to render the code. Gave it a shot using a bit of JavaScript, since that's what I'll be using most of the time.

var links = document.querySelectorAll('a');
var hrefs =, function (link) { 
    return link.href; 

For now will do just fine, using the colorful preset and stripping the border. It makes the code stand out, displays JavaScript and line numbers just fine and that's about all I want from it for now.