Friday, 6 February 2015

Procedural Generation - Part Five : Surprise (Browser-Compatibility) Monster Attack!

Surprise Attack! If you visited the previous dungeon examples in a non-Chrome browser, you may have noticed two issues. One was that the graphics looked all blurred and the other being that the sound didn't play. Let's roll a couple of D6's and see if we have the agility to overcome it!

Firstly, why is it blurry? This is due to browsers smoothing scaled images on the canvas by default. For pixel based art (blocky), we do not want this to happen so we have to use the property imageSmoothingEnabled of the drawing context object that we get from the canvas. Currently in Dart, this property doesn't cover the numerous variants. If we want the dungeon to work on IE, Firefox etc we need to use JavaScript.

Fortunately calling JS from Dart is very easy. We will add a simple class to the index.html page with a simple class called crossBrowserFilla with a single method called keepThingsBlocky.


    var crossBrowserFilla  = function (){

      this.keepThingsBlocky = function(){
        var canvas = document.getElementById("surface");
        var ctx = canvas.getContext("2d");
        ctx.mozImageSmoothingEnabled = false;
        ctx.imageSmoothingEnabled = false;
        ctx.msImageSmoothingEnabled = false;
        ctx.webkitImageSmoothingEnabled = false;
      }
    };
  

This is called in main.dart. Fairly easy!

import 'dart:js';

....

JsObject jsproxy = new JsObject(context['crossBrowserFilla']);
bool canvasConfigured = false;

...

    if (!canvasConfigured){
      jsproxy.callMethod('keepThingsBlocky');
      canvasConfigured = true;
    }

The second issue of sound has to navigate things a bit differently. The best format across browsers is MP3 currently, the downside being is that Dartium doesn't yet support the required codec as it is based on Chromium. This is short term (hopefully) once the Dart VM makes it into Chrome. Apart from changing the file extensions, there is not change required to the audio code.

Code is available on Github and a live demo is available here. Use arrow keys to move!

Next time we will REALLY REALLY WILL finish our dungeon adventures by putting some other characters in the dungeon. A wizard's promise!