All the FP talks at NDC London

So NDC Oslo has come and gone, and whilst we wait for the videos for NDC Oslo to be available here are all the FP talks from NDC London this year.

Enjoy 

 

Having fun with HTML5 – Simple painting app using Canvas

It feels like a little while since I last played around with the <canvas> element, so I spent some time over the weekend and put together a simple painting app using the canvas and here is the end result.

Here’s some screenshots:

image image image

Spray Tool

One of the interesting things with this simple painting app is the spray tool, here’s what I did to achieve the effect:

   1: var _intervalId,    // used to track the current interval ID

   2:     _center;        // the current center to spray

   3:

   4: function getRandomOffset() {

   5:     var randomAngle = Math.random() * 360;

   6:     var randomRadius = Math.random() * radius;

   7:

   8:     return {

   9:         x: Math.cos(randomAngle) * randomRadius,

  10:         y: Math.sin(randomAngle) * randomRadius

  11:     };

  12: }

  13:

  14: this.startDrawing = function (position) {

  15:     _center = position;

  16:

  17:     // spray once every 200 milliseconds

  18:     _intervalId = setInterval(this.spray, 10);

  19: };

  20:

  21: this.finishDrawing = function (position) {

  22:     clearInterval(_intervalId);

  23: };

  24:

  25: this.spray = function () {

  26:     var centerX = _center.X, centerY = _center.Y, i;

  27:

  28:     for (i = 0; i < density; i++) {

  29:         var offset = getRandomOffset();

  30:         var x = centerX + offset.x, y = centerY + offset.y;

  31:

  32:         drawingCxt.fillRect(x, y, 1, 1);

  33:     }

  34: };

The startDrawing function is called when the mouseDown or a subsequent mouseMove event is raised, it in turn sets up an interval event which is triggered every 10 milliseconds and draws one pixel using the currently configured colour within the radius of the mouse pointer.

When the mouseUp event is raised, the interval event handler is unbound.

Saving the Canvas to an Image

One of the cool things you can do with the <canvas> element is the ability to get a data:URL containing a representation of the image as a PNG file, which you can then use as the source for an <img> element so that the user can then save.

The code required to do this is as simple as calling toDataURL() on the <canvas> element and then use the returned value to set the src property on the <img> element.

Demo

You can try out the live demo at http://sketchy.theburningmonk.com or via the shortlink http://lnk.by/fghis.

If you’re interested in the source code, you can get it off github here.

 

Enjoy!

Reactive Extensions for Javascript – Observable vs ConnectableObservable

For those of you who are familiar with Reactive Extensions you should know all about observables already, but did you know that there’s another kind of observable sequence – Rx.ConnectableObservable.

The difference between the two types of observable sequences is well explained here, in short, a connectable observable sequence allows you to share the same source sequence of values with multiple subscribers whilst the normal observable sequence gives each subscriber its own sequence of values. Whilst in most cases this difference doesn’t have any practical impacts as each subscribers are given the same values in the same order, however, consider this observable sequence of random numbers between 0 and 1000:

   1: var maxNumber = 1000;

   2: var observableSource = Rx.Observable.GenerateWithTime(

   3:     Math.random(),                                      // initial state

   4:     function (x) { return true; },                      // condition

   5:     function (x) { return Math.random(); },             // iterator     

   6:     function (x) { return parseInt(x * maxNumber); },   // select

   7:     function (x) { return 1000 });                      // interval

As you can see, each time the iterator is invoked it’ll generate a different value, hence subscribers will receive a different value each time (see demo below):

   1: // first subscriber

   2: observableSource.Subscribe(function (n) {

   3:     sub1Span.html(n);

   4: });

   5:  

   6: // second subscriber

   7: observableSource.Subscribe(function (n) {

   8:     sub2Span.html(n);

   9: });

Instead, if you want to ensure that all the subscribers receive the same values, your best bet is to ‘publish‘ the source:

   1: // create a connectable observable from the source

   2: var connectableObservable = observableSource.Publish();

which returns you a connectable observable that you can then attach subscribers to:

   1: // connected subscriber 1

   2: connectableObservable.Subscribe(function (n) {

   3:     connSub1Span.html(n);

   4: });

   5:  

   6: // connected subscriber 2

   7: connectableObservable.Subscribe(function (n) {

   8:     connSub2Span.html(n);

   9: });

and once you ‘connect‘ to the underlying source, the subscribers will start receiving values from the stream:

   1: connectableObservable.Connect();

Demo

Reactive Extensions for Javascript – Causing side effects with Do

I wrote previously about how you can set up multiple observable sequences and subscribe to them with multiple observers and create a many-to-many relationship between them.

Whilst this is a very flexible model with a clear separation of responsibilities, often it requires more work to set up and is more than what you need for the task at hand. For instance, if you’re receiving a steady stream of inputs and want to log the arrival of new inputs as well as performing some aggregation on them, you don’t necessarily have to create two subscribers for the input but instead make use of the Rx.Observable.Do function.

Like the Rx.Observable.Subscribe function, the Do function can take a subscriber, or two up to three function objects to handle the onNext, onError and onCompleted events, in that order. Unlike the Rx.Observable.Select function, it doesn’t have a return value and therefore won’t allow you to transform the input stream, it’s intended purely for causing side effects.

I’ve put together a quick demo (see below) to illustrate the use of the Do function in conjunction with other common RxJS functions such as Select and Where. For this demo we just need two <span> elements, one to show the running total, the other to show a log message every time a new value is received:

   1: <body>

   2:     <div id="wrapper">

   3:         <p>Sum of squares of odd numbers received : <span id="sum"></span></p>

   4:         <p><span id="log"></span></p>

   5:     </div>

   6: </body>

And the Javascript to go along with it:

   1: <script type="text/javascript" src="js/jquery/jquery-1.4.4.min.js"></script>

   2: <script type="text/javascript" src="js/rxjs/rx.js"></script>

   3:  

   4: <script type="text/javascript">

   5:     $(function () {

   6:         var logSpan = $("#log"), sumSpan = $("#sum");

   7:  

   8:         // create an observable which gives ten numbers in total at 1 second 

   9:         // interval with a 13% chance of exception being thrown at each interval

  10:         var observable = Rx.Observable.GenerateWithTime(

  11:             1,                                  // initial state

  12:             function (x) { return x <= 10; },   // condition

  13:             function (x) {                      // iterator

  14:                 var prob = Math.random();

  15:                 if (prob < 0.13) {

  16:                     throw "Better luck next time!";

  17:                 }

  18:  

  19:                 return x + 1;

  20:             },

  21:             function (x) { return x; },         // select

  22:             function (x) {                      // interval

  23:                 return x === 0 ? 0 : 1000

  24:             });

  25:  

  26:         var sum = 0;

  27:  

  28:         observable.Do(function (n) {    // onNext

  29:             logSpan.html("Received new input: " + n);

  30:         }, function (err) {             // onError

  31:             logSpan.html("Error: " + err);

  32:         }, function () {               // onCompleted

  33:             logSpan.html("No more inputs");

  34:         }).Where(function (n) {         // filter the input sequence

  35:             return n % 2 != 0;          // odd numbers only

  36:         }).Select(function (n) {        // transform the input sequence

  37:             return n * n;

  38:         }).Subscribe(function (n) {

  39:             sum += n;                   // add the new input to the running total

  40:             sumSpan.html(sum);          // show the new running total

  41:         });

  42:     });

  43: </script>

Couple of things to note here:

  • line 13 – this is a deliberate attempt to give the observable sequence a random chance of excepting to invoke the onError handler specified in the Do function on line 30
  • line 28 – the Do function updates the HTML content in the log <span> element every time it receives a new value
  • line 32 – show a different log message when we have exhausted the observable sequence
  • line 34 – apply a filter on the observable sequence for all subsequent functions
  • line 36 – only odd numbers are fed to this handler

Demo

If you are lucky enough (or unlucky enough depending on which scenario you’re trying to test) just refresh the page and try again and hopefully you have better luck the second time around!

Reactive Extensions for Javascript – Wikipedia lookup demo

Matthew Podwysocki posted a couple of very good articles on RxJS on codebetter.com and amongst them was a simple demo to do a look up on wikipedia using their open API:

Introduction to the Reactive Extensions for JavaScript – Wikipedia Lookup

Unfortunately, there wasn’t a live demo you can play around with and see it work, and since the article was posted things might have changed and doing cross-domain HTTP requests are no longer a straightforward affair (at least not when it comes to Chrome and Firefox). If you had tried to piece together all the bits of code snippets from the article you might find that it only works in IE but not in Chrome or Firefox.

So I decided to put together a working demo, and with that, let’s start with the HTML from the original example:

   1: <body>

   2:     <div id="wrapper">

   3:         <input id="search-input" size="100" type="text" placeholder="Enter Search Phrase" />

   4:         <ul id="results" />

   5:         <p id="error" />

   6:     </div>

   7: </body>

And the Javascript which had been slightly modified from those shown in the article:

   1: <script type="text/javascript">

   2:     function searchWiki(term) {

   3:         // note the callback=? clause at the end, which is required to make 

   4:         // cross-domain request possible in chrome and firefox

   5:         var url = "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + 

   6:                     term + "&format=json&callback=?";

   7:  

   8:         // note that I'm using getJSONAsObservable instead of XMLHttpRequest

   9:         return $.getJSONAsObservable(url)

  10:                 .Select(function (result) {

  11:                     if (result.data && result.data.length == 2) {

  12:                         return result.data[1];

  13:                     }

  14:                     else {

  15:                         return [];

  16:                     }

  17:                 });

  18:     }

  19:  

  20:     $(function () {

  21:         var searcher = $("#search-input");

  22:  

  23:         var searchTerms = 

  24:             searcher.toObservable("keyup")     // hook up the keyup event on the search box

  25:                     .Throttle(250)             // ignore values entered within 250ms of each other

  26:                     .Select(function () {      // return what's in the search box

  27:                         return searcher.val();

  28:                     });

  29:  

  30:         var searchResults = searchTerms.Select(function (term) { return searchWiki(term); }).Switch();

  31:  

  32:         searchResults.Subscribe(function (data) {

  33:             $("#results").empty();

  34:             $.each(data, function (_, value) {

  35:                 $("#results").append("<li>" + value + "</li>");

  36:             })

  37:         }, function (errr) {

  38:             $("#error").html(error);

  39:         });

  40:     });

  41: </script>

Key things to note here:

  • line 6, at the end of the url I added &callback=? which is the standard way to specify a JSONP callback with jQuery‘s getJSON function.
  • line 9, I used getJSONAsObservable, which is the same as getJSON but returns the values as an observable sequence

Demo