Javascript: Mixins in AngularJS

We’ve been doing a bit of AngularJS work (more on that later) recently and true to its reputation there’s an “Angular way” to accomplish most things. Interestingly, one area where I couldn’t find a “one true way” was how to facilitate mixins between controllers or scopes.

Quickly taking a step back, a “mixin” is a form of horizontal reuse that allows two objects to share code without necessarily sharing a common ancestor in an inheritance chain. With concrete examples, you might have a Dashboard and Billing controller which need to share formatting logic but nothing else you’d want to use mixins vs. traditional inheritance. In traditional object oriented language mixins are typically referred to as Traits.

Anyway, back to AngularJS. Let’s say we have some simple logic that we want to share between two scopes:

It’s a contrived example but the “idea” is that you want to share the “selectAnswer” and “getAnswerClass” functions between $scopes of two unrelated controllers. After doing some research, it seems like the cleanest way to do this in Angular is to create a service that contains the functions, inject that into the controller, and then use angular.extend() to add them to the $scope as needed:

And that’s pretty much all there is to it. I’m pretty new to the Angular dance so I’d love any feedback!

Javascript: Building a HTML5 canvas puzzle

As promised, here’s the follow up on my previous post Javascript: Using Canvas to cut an area of an image where we looked at how to use Canvas to cut a mask out of an image. To quickly recap, in the last post we looked at how to crop a patterned mask out of an image using a HTML5 Canvas. Using this technique, you’d be able to provide an image that looks something like:

So how do you go about making a puzzle? You can see the end result at HTML5 Canvas Puzzle and the code is online at https://github.com/Setfive/setfive.github.com/tree/master/canvas_puzzle.

As it turns out generating an arbitrary puzzle programatically is reasonably complicated. The best explanation I could find on how to accomplish this is at https://www.allegro.cc/forums/thread/586750/603411#target. Conceptually, the process looks straightforward enough and you could probably manually do it on a whiteboard. Unfortunately, the issue I ran into with this approach is that drawing bezier curves and splines programmatically on a Canvas is a bit involved. I also don’t have a background in vector graphics so I was getting stuck in the weeds drawing lines.

Discounting generating the puzzle entirely on the fly, an alternative approach would be to use a fixed set of available pieces and then “fill in” a grid depending on how large the image area is. Conceptually, the idea is to construct a closed grid of pieces where some number of the pieces can be repeated and then repeat those pieces as needed to cover the target image. The templated pieces I used are in /puzzle_pieces/.

Technically, I decided to use fabric.js to facilitate Canvas interaction along with lodash.js and of course the ubituqous jQuery.

Walking through the code, the steps to build a puzzle are fairly straightforward:

  1. Load images: The first step is to load all the template images and target image so that they’re available to use on a Canvas. Since jQuery is available, one approach is to create a deferred for each image, resolve it as the image loads, and use $.when to wait for all of the images to load. See here for example.
  2. Build pieces grid: Next you’ll need to figure out how many repeated pieces you need to fill into the grid. One issue here is that since the puzzles need to fit snuggly the image dimensions of a given piece won’t be what you need to use to calculate the grid. Because of this, I ended up with a bit of goofy code for this.
  3. Create image masks: Once you have the number of pieces to create you’ll need to cut masks for each piece out of the source image and create fabric.js objects for them. See copyImageChunk.
  4. Place masks: Placing the “pieces” is also complicated because of the dimension issue above. See kludgy code.
  5. Shuffle and track movements: Finally, you just need to shuffle the positions of the images and then track their movement to report a “correct” position.

And that’s about it. One other “trick” is that you can use Window.requestAnimationFrame to avoid locking the UI when you’re creating the masked images since it’s a compute intensive task.

Anyway, as always questions and comments welcome.

Javascript: Using Canvas to cut an area of an image

Over the few weeks I’ve been working on a Canvas based side project (more on that soon) that involved cutting a mask out of a source image and placing it on a Canvas. In Photoshop parlance, this would be similar to creating a clipping mask and then using it to extract a path from the image into a new layer. So visually, we’re looking to achieve something similar to:

At face value, it looks like doing this with Canvas is pretty straightforward using the getImageData function. Unfortunately, if you look at the parameters that function accepts it’ll only support slicing out rectangular areas which isn’t what we’re looking to do. Luckily, if you look a bit further in the docs it turns out Canvas supports setting globalCompositeOperation which allows you to control how image data is drawn onto the canvas. The idea is to draw the mask on a canvas, turn on the “source-in” setting, and then draw on the image that you want to generate the slice off. The big thing to note here is that putImageData isn’t effected by the globalCompositeOperation setting so you have to use drawImage to draw the mask and image data.

So concretely how do you do this? Well check it out:

The code is running over at http://symf.setfive.com/canvas_puzzle/grass.html if you want to see it in action.

Anyway, happy canvasing!

Fun: Sending Valentines day cards with lob.com

A couple of months ago I ran across the lob.com API on ProgrammableWeb and was intrigued. One of the features of the Lob API is that it allows you to programmatically send postcards by just providing address details and images. I’d been itching to find a use case for the API since who doesn’t love physical mail? Following a few beers on a snow day an idea struck – why not send Valentines day postcards with lob!

Overall, the idea was straightforward, allow users to compose a message on one of a few available templates, enter some address details, and then send their postcard. Given the short timeline and relatively few features, the main factors behind picking an implementation stack were something “lightweight” that I was already comfortable with. After drawing up some options I decided to use Silex since it’s based on Symfony components, it’s lightweight, and we’ve used it in the past.

The main UI for the cards ended up looking like:

One of the “fun” features I did implement was that instead of using a big header background image, I used a HTML5 Canvas to render frames from Beauty and the Beast as the page’s background.

Anyway, we might bring this back next year so be on the lookout around Valentines day.

Scala: Fun with Parser Combinators

A couple of months ago I decided to use Scala with the Play Framework for a Bitcoin related project. The decision to use Play was motivated primarily by the goal of implementing a “pure” Bitcoin application, leveraging bitcoinj to interact with the Bitcoin network as opposed to a third party service. Overall, everything was pretty straightforward but one thing that stuck out was how the Play framework handles parsing JSON.

Coming from loosely typed PHP I knew that handling serializing and unserializing of JSON data was going to be different but Play’s approach is a completely new paradigm. If you use Play with Scala, you can handle parsing JSON input back into objects using Scala’s Parser Combinators syntax. I’m going to butcher this description so check the wikipedia entry but the idea is that parser combinators let you “build up” increasingly complex parsers by combining functions that recognize smaller inputs. If you’ve taken a compilers or programming language class, Scala’s parser combinators end up looking a lot like Backus–Naur Form for the input you want to recognize.

Anyway in an effort to learn Scala a bit better and take Parser Combinators for a spin I decided to build out a small project. What I ended up building is a really simple implementation of a Turtle Graphics system. You basically feed it a series of “turtle” commands and it’ll move the “turtle” around on a Swing window drawing some graphics.

Here’s an examples of the input and output:

Which was generated by:

Overall, parser combinators seem to be a really powerful Scala feature that would make developing domain specific languages relatively straightforward. Compared to messing around with a parser generator, using parser combinators seems to more closely mirror what the formal grammar of a language would be.

The entire project is available on GitHub. If you clone that project, there’s a runnable JAR which you can run with:

java -jar logoparser.jar /home/ashish/workspace_java/logo-parser/samples/face.txt

You’ll need to provide an absolute path for the “filewatcher” to work. Once the app starts, if you modify the file you specify it’ll repaint the canvas with your updates. Note: I’m not sure why but certain text editors don’t seem to register in the Java “filewatcher” interface so if your updates aren’t showing up try using a different editor.

Anyway, as always I’d love any feedback!