Categories
Web Technology

Things that are Awesome about AngularJS

This post was so popular I wrote a book about ramping up on AngularJS. It’s available in eBook and paperback if you’d like a copy.

We host talks at Netflix every Monday, and today’s talk was from a couple of Google employees that work on AngularJS — one of those new-fangled Javascript frameworks (like Ember, Knockout, Backbone, etc).

In no particular order, here are some thoughts I happened to write down during the two-hour talk:

HTML5 Fallbacks

I noticed a couple of places where Angular seems to be doing something that I know is a planned feature in HTML5 (field-level validation, web history via JS).

At first, I thought this was kind of stupid. What are you going to do when those features become mainstream? I don’t want to have to choose between the proper, standards-specified way of doing something, and the way this framework wants me to do it. That would be super-lame.

Eventually I caught on that they’re providing a framework way to do it, but they seem to be falling back on the HTML5 versions when supported. This was very clear in the web history example, where the speaker mentioned they convert from hash-bang syntax to proper HTML5 history API calls, but I caught a bit of it during the validation example as well.

This is actually kind of cool. They’re making the features available right now, but putting the framework (and by extension, the apps built using the framework) in a position where transitioning to the standard HTML5 solution will be easy when that solution becomes widely available.

In short, you get to use soon-to-be-standard HTML5 features now, and it will be easy to convert your app to use HTML5 standards later. Neat!

HTML5 Future-Mindedness

Along the same lines, the team at Angular seems to have put a lot of effort into helping you get your application (and skillset) ready for the future of HTML5. Here’s an example:

One of the HTML5 features I’m most excited about is Web Components. We’re still at least 6 months away from seeing these in beta release channels (Aurora, Canary, etc), but they’re available in the Safari and Chrome nightlies right now.

Web Components are going to change how plugins and widgets are developed across the web. (It’s going to get a whole lot easier for everyone.) They’ll herald in a fundamental change from Javascript-based widgets (see most jQuery plugins) to HTML/CSS-based widgets that perform better, cause less naming conflicts, and integrate better into both standalone websites and Javascript applications.

What I love, love, love about reusable components in AngularJS is that they follow the same paradigm shift. The way you write and use reusable components in AngularJS looks and feels a whole lot like how you’ll write and use web components in a couple of years.

This is super-helpful for the web developer community. Web components are the future, and Angular’s reusable components are a very similar present.

Good Web Citizenship

My main gripe with a lot of frameworks these days is that they don’t play nice with the rest of their world.

Just today, for example, one of my coworkers went on a rant about how some Node-based packaging plugin he was looking at tried to force its own conventions on the content you’re trying to package. This is a huge no-no! A good framework goes out of its way to make sure it can work with as wide a range of content as possible.

AngularJS is one of the good guys.

Need your HTML to validate? They provide a slightly-more-verbose syntax for that. Want to minify your dependency injections? You can do that too, just add an extra line of code. Want to integrate with jQuery or Node or your favourite test framework? No problem!

The web is a heavily-interconnected place, and it’s nice to see frameworks put some effort into fitting in. People aren’t going to use your library if it conflicts with anything they’re already doing/using.

Dependency Injection!

Did your heart skip a beat when I mentioned this a second ago? It should have.

I’m not going to advocate that all JavaScript applications would benefit from dependency injection, but I bet most of the kinds of apps people build with frameworks like AngularJS absolutely will. You get to write less code, you don’t need to worry about the boilerplate of managing dependencies, and it’s just so much more fun to have a smart library handle this for you.

Even if you’re not a fan of dependency injection, I still think you should be excited about this. We need more experimentation with server-side features. If the success of Node has taught us anything, it’s that JS developers want to write server-ish code if it will help them get the job done quicker. Experimentation must be encouraged!

Unit Testing is a Big Deal

I didn’t count how many times our speaker mentioned unit tests, but I’m fully confident it was at least two dozen times.

I know what you’re thinking: Dan, every framework wants you to write unit tests.

You’re right, but most frameworks don’t put anywhere near this much focus on testing. It’s not some after-thought they tacked on to attract the TDD crowd. There’s support for testing in the docs, and every aspect of an Angular application is fully testable. Our speaker discussed integration with Jasmine, Testacular, and Selenium.

It’s always great to see frameworks (and their communities) encourage testing, and the level of testing support for AngularJS is especially notable for how new(ish) the framework is.

The Usual Suspects

Like every other JavaScript framework ever, AngularJS has all the staples:

  • Template support,
  • data binding,
  • work-in-progress documentation,
  • and a handful of useful UI components.

Next time I find time to build a fun little webapp, I’ll probably give AngularJS a shot. I was seriously impressed by all the thought they put into making their features HTML5-ready, and little extras like dependency injection and seriously overwhelming testing support are just icing on the cake.

I’ve been away from the JS framework scene for a little while now. Did I miss anything? Is this all old news? What are the all cool kids using these days?

Categories
Web Technology

Brand New Adobe

Adobe is changing. The once-great giant of web and web tools has fallen, and is poised to rise again — albeit in a much different form. What does this mean for us web developers?

For starters, let’s go over some recent news. Adobe made three major announcements in the past six weeks that will have sweeping implications on their image. See if you can spot a trend in these headlines:

What do these press releases have in common? If you caught that all three are about open technology, give yourself a pat on the back. Let’s dig into the facts before discussing the ramifications.

Adobe has seen the light, and open source is sparkling.

Closed formats are dying across the web. The days are numbered for plugins like Silverlight and Flash; they’re simply not necessary anymore for the vast majority of sites and applications. HTML5, on the other hand, is thriving. We’re starting to see open fonts pick up, and even longtime-stalwarts MP3 and MPEG-4 are starting to lose their grasp of the online audio/video markets.

Adobe isn’t blind. They know they need to transition away from closed platforms. Picking up PhoneGap shows their commitment to this cause.

Re-aligning their mobile efforts towards HTML5 is another positive step towards open technology. Adobe still makes some of the web’s best tools, and Javascript development could seriously use an outstanding IDE. This seems like a great match-up.

Finally, releasing Flex to the community is a smart move. There is a very vibrant community around Flex, and there are still niches where RIA will matter for a little while longer. If Adobe can’t support Flex on its own, enabling the community to take control of it’s own future simply makes sense.

Adobe’s intentions are clear. Proprietary formats are out, the open web is in.

What does this mean for web developers?

Three things:

First and foremost: Learn your shit. If you’re a web developer, learn everything you can about Javascript, HTML5, CSS3, and the myriad of related frameworks. These will only become more important following the fall of Flash.

Second: If you’re a Flash/Flex dev, start looking at Sencha. At SenchaCon last month, the number-one answer I got back when I asked people what they worked in before switching to Sencha was Adobe Flex. And I believe it. I’m a Flex guy too, but that market’s shrinking quickly. Sencha is going to be a major player on the web for a while to come, and it’s a relatively smooth transition.

Third: Get into mobile. Adobe didn’t pick up PhoneGap just to gain FOSS-cred. Mobile is huge. Huge! This is where you want to be right now, and you can join in using Javascript and Sencha and many other web technologies.

This is an exciting time to be in web development. Let’s keep on top of the constantly-changing platforms and tools. Let’s keep building wonderful things. Let’s make this an age to be proud of when they talk about the day Adobe changed their ways.

Who’s with me?

Categories
Web Technology

My SenchaCon Hackathon Entry

The last day of SenchaCon was a hackathon, where everyone that stuck around (probably over 100 people) grouped together and hacked away to see who could make the coolest one-day project. There were a LOT of great apps, and several came away with cash and prizes (all of it very well earned!).

Not featured in the winners list is the app I made, because I missed the submission deadline by about twenty minutes. All this because I lost far too much time debugging issues with HTML5’s native drag-and-drop API. (I was planning on writing a rant about it, but Quirksmode beat me to the punch.)

In any event, I’ve uploaded the incredibly raw creation, and you can now play my simple HTML5 Video Puzzle Game. I only tested in Chrome, but it seems to run alright in the latest Aurora build of Firefox. Basically the app loads up an HTML5 video, slices it into 16 canvases, and scrambles the pieces. Your job is to re-arrange them by dragging them back into place (using HTML5’s native drag-and-drop, of course).

It’s really, really unpolished. I spent all of about 8 seconds on the styling, and there are a lot of features that are complete but inaccessible (like slicing the video into more pieces). I might try to fix it up later.

Anyway, the whole day was a lot of fun, just like the rest of the conference. It would be awesome to go again next year. We’ll see!

Until then, happy hacking, all my fellow attendees!

Categories
Software Development Web Technology

How to Make a Colour Selector with HTML5 Canvas

Over the weekend, I attended HackOTT, a hackathon here in Ottawa that encouraged everyone to play around with some neat third-party APIs. It was a lot of fun seeing the awesome apps everyone came up with, and even though we didn’t get to demo, I’m happy with how much I learned.

My team was comprised of myself, my softball captain/ex-coworker @jyboudreau, and our fearless leader @davefp. The idea was that we would create an HTML5 application that allowed users to upload an image of a room, select a few colours from that image, and get back a list of products sold through Shopify that match the room. We were pretty excited, and so were some of the API guys we talked to.

Dave and JY grabbed the TinEye and Shopify APIs, so that left me with the UI. While we didn’t quite manage to get everything working in time to demo, we did make a lot of progress, and I thought I’d share part of my contribution, a Canvas-based app that lets the user pull colour swatches out of an image.

Let’s look at how it works!

Basic Setup

The layout is pretty simple. The empty blocks on either side are just divs that will hold our colour swatches, and that image in the middle is actually a canvas. In fact, it’s two canvases, overlayed on top of each other using some absolute positioning.

We used two canvases to make the drawing easier. The backmost canvas holds our image, and that’s it. The frontmost canvas, which is completely transparent, is where the swatch outlines are drawn. This makes it less expensive to redraw swatch outlines, because we don’t have to reload the image each time, and allows two swatch outlines overlap without having them affect one another’s colour.

Now, let’s have a look at the drawing code.

Loading the Image

Loading an image into a canvas is relatively straightforward. Check out the javascript file, and in particular note the addUserImage function. The mechanics of loading an image are simple:

  1. Create a new logical image:
    var img = new Image();
  2. Make sure the image’s onload function ends by drawing the image:
    context.drawImage(img,0,0,img.width,img.height);
    
  3. Trigger onload by setting the image’s src property:
    img.src = TEST_IMG;
    

There are a couple of gotchas, though:

First, you may have noticed that in the image’s onload lamba, we’re adjusting the dimensions of both canvases and their container. This resizes our canvases and the surrounding layout to match the size of the image. We also set the canvases to display block because they are hidden by default (this avoids an ugly resizing-flash right after the page loads).

Second, the image src can’t be just any image. For canvas to load it properly, it must be an image contained within your own domain. This means you can’t just give it a url you found online, or even load it from a file using localhost. We deployed our app using App Engine, but any container should do the job just fine.

That’s all there is to loading an image, let’s move on to swatches.

Drawing the Swatch Outlines

There are three user events we care about for our canvas: mousedown, mousemove, and mouseup. To handle these events, there are three functions: handleCanvasClick, handleCanvasMouseMove, and handleCanvasMouseUp. Let’s look at these a little more in-depth.

First, you’ll notice that each function uses some simple math to get the coordinates of the mouse click:

var clickX = event.pageX - canvas.offsetLeft;
var clickY = event.pageY - canvas.offsetTop;

We get the coordinates from the page via event.pageX, then subtract the top-left corner of the canvas so that we’re left with the distance of the click from the canvas’s top-left corner. Conveniently, the origin for canvas is located in the top-left corner, so we’re already in the right coordinate space and our x/y positions are ready to use.

Next let’s talk about getSwatchIndex(). This is a convenience function that parses the id of the currently-highlighted div to give us a numerical representation. Why is this important? Because we want to maintain an array that represents the current position of each swatch outline, and we use these numbers to index it.

By storing the positions of the swatch outlines in an array, we’re free to clear the swatch-outline canvas and redraw it completely on each pass. This might seem like overkill, but it’s necessary for situations where two swatch outlines overlap, and at a code level, it’s less work than repainting a transparent box over a swatch outline before the swatch outline is painted again it in its new position.

Once we’ve updated our array, it’s off to our redrawSwatches function to actually draw them. The algorithm here is what you would expect, we loop over the array of swatch outline positions, and draw each one with a semi-transparent background and a solid border. We’re also watching for the currently selected swatch index to come up, because we want to highlight that border with a brighter colour so that the user knows which swatch outline is active.

Handling Dragging

We wanted the user to be able to drag a swatch outline around to make sure it’s placed in exactly the right spot. This ended up being easier than we thought. You may have noticed the dragEnabled variable in our mouse event functions. This is a global boolean that we set on mousedown and clear on mouseup. That way, when mousemove fires, we can check it and redraw if a drag is occurring. Simple!

Extracting Colour Information

Let’s head back to handleCanvasMouseUp and look at the colour extraction (which should probably be in its own function).

The important step is this one:

var imageData = context.getImageData(
    clickX,clickY,HIGHLIGHT_SIZE,HIGHLIGHT_SIZE).data;

Here we’re telling the canvas to give us the image data for a square positioned where the user clicked, and the size of our swatch outline (that I for some reason called a highlight this time &#151 we were in a rush). That returns canvas’s own ImageData object, which probably does all kinds of neat things, but we just wanted the pixels, so we called .data to grab them.

Pixel data in canvas is stored as a giant rgba array. So if you have a 10×10 canvas, then the array will be of size 400 (10x10x4) and will be formatted as [r1, g1, b1, a1, r2, g2, b2, a2, etc]. We want the rgb values only (we skip straight over the alpha values in this case), so we sum up all of the reds, blues and greens individually.

Finally, we average out each colour by dividing it by the number of pixels, floor the totals to get integer values, and voilà! We have an average colour we can show in the swatch.

It was fun spending the day playing around with canvas. Hopefully next time we’ll get something we can demo!

Categories
Web Misc

Elsewhere: HTML5 and Browser Testing

I wrote a couple of posts for work last week:

Hopefully those will be of interest to you if you’re into techie web stuff.

This week’s post for this blog is a bit more opinionated than usual, and is taking longer as a result. It probably won’t be up until tomorrow. But it’s going to be my first post (ever!) about copyright, which is something I can get a bit touchy about, so you don’t want to miss it.

Categories
Web Misc

Why HTML5 Makes Sense for Mobile

These days there are more and more mobile devices that support rich software applications. Since the iPhone, we’ve seen the Blackberry, the Palm Pre and Android all start their own app stores, and surely Windows Phone 7 won’t be far behind. With all of these options, how do you decide which ones to develop software for? Porting the same native application to five different platforms is expensive, but only supporting a few adds the risk of alienating users with non-supported devices. Fortunately, thanks to HTML5, it’s now possible to develop one version of your application that works across all these platforms.

HTML5 is a new standard for developing web-based applications with rich interfaces similar to what can traditionally only be achieved in a desktop environment or by using browser plug-ins such as Adobe Flash. Support for HTML5 is being built right into all modern web browsers, with many features already available. While this is very good for the web community, it’s also very good for the mobile space; all modern smartphones come with a browser that is working to support HTML5. This means that instead of re-writing the same application for each mobile platform, one single version can be written in HTML5 that works across all of them.

The main motivation for choosing HTML5 is that the smartphone market is diverging, while support for HTML5 is converging. Each mobile platform in the expanding mobile space has its own API and distribution model, and any new platforms will likely follow suite. Contrast this with support for HTML5, where all these platforms are rushing to implement the same specification. How will this look in a few years? We will have even more platforms to develop separate clients for, but all of them will have increasingly better support for HTML5.

Another big reason for choosing HTM5 is that it has a strong, predictable future. In addition to picking up traction all over the web, the specification for HTML5 is mapped out to the year 2022, over ten years from now (but that doesn’t mean HTML5 is not ready to use right now). With the current smartphone market, it’s difficult to predict which clients will even be around in a few years, let alone which ones will still be popular. Using an HTML5 client removes much of the guesswork surrounding which platforms to support, and as it becomes the default standard for web browsers, any future platforms will support it as well.

There are other benefits to an HTML5 client, such as the control it grants you over your application. With the iPhone, for example, Apple must approve any change that is made to a native application, even after it is released. With an HTML5 application, there is no need for an approval process — in fact, it’s not even possible; device manufacturers and OS providers have no ability to regulate web content.

HTML5 is a great choice for mobile development in the current market. If you find yourself struggling to decide which platform(s) to develop for, or concerned about the future landscape of the mobile space, or unsure about having to seek approval from a manufacturer before your application can be deployed, consider the possible advantages of HTML5; it won’t be right for every scenario, but creating a native app isn’t either.

Note: This post is also available at http://www.macadamian.com/blog/post/why_html5_makes_sense_for_mobile/.

Categories
Web Technology

The Present and Future of Flash

Adobe Flash is at an interesting point in its existence. For about a decade, it was the only way to get rich, dynamic content onto the web. If it was the year 2001 and you wanted a really sleek UI, or video, or any kind of animation, Flash was your best bet — it was pretty much a monopoly. Then things started to change:

  • DHTML started to take over some of the really basic use-cases for dynamic events like rollovers and showing/hiding content.
  • AJAX made truly dynamic content easier for the non-flash world.
  • The mobile web started to take off, with most devices not capable of supporting Flash.
  • Microsoft released Silverlight, a competitor to Flash in the rich interface space.
  • Apple started releasing wildly popular devices that intentionally avoided supporting Flash.
  • Browsers started implementing support for HTML5 and CSS3, which are slowly being adopted by designs that would historically require Flash.

Slowly but surely, alternatives to Flash have been picking up speed, and things beyond Adobe’s control have prevented Flash from penetrating certain markets (mobile in particular). What does this mean for Flash as a technology?

Flash isn’t going away anytime soon…

This isn’t one of those posts about how HTML5 or the iPad or global warming is going to spell the end of Flash. Flash is a major player in many areas of the web, most of which won’t change anytime soon. In particular:

Games — There are tons of online Flash games. This is a huge market that Flash has absolutely dominated since day one, and none of the technologies mentioned above can compete with Flash on this level of interactivity.

Video — Like it or not, HTML5 is not yet strong enough to handle cross-browser, web-based video. Even when it is (and it will be sooner than you think) Flash will still be used well into the future because it’s the only solution for legacy browsers, and the vast majority of users don’t update their browsers as often as they should.

On top of that, Adobe has created an entire ecosystem of software and a vibrant community for designing, building, and publishing Flash-based applications. Plenty of people are heavily invested in these tools, and no amount of evangalism is going to convince them that their problems could be better solved by today’s Flash-alternative du jour.

…but Flash will start having a reduced role on the web in general.

It would be unrealistic to pretend that these new technologies aren’t eating into Flash’s market share. For one, even in the most complex cases, some projects are choosing Silverlight over Flash. Not the majority (not even close) but more than none, and Microsoft is a powerful competitor that can compete with Adobe on the development tools and community levels.

Secondly, HTML5 and CSS3 can do some pretty neat things. For cases such as modern, dynamic navigation and simple logo animation, it will soon make much more sense to use features supported by the browser than a heavyweight proprietary plug-in; especially if all you need is a quick piece of eye candy.

Finally, there are the problems caused by Apple. I can think of three:

No iPad/iPhone Support — The longer this keeps up (and I don’t see it changing anytime soon), the more likely it is that someone will create a cool, interesting way to do fancy, Flash-like things in an iFriendly format. And then a general-mobile format. And then a web format. The last thing Flash needs right now is for some brilliant start-up to shake things up even further.

Macbooks are getting popular — Adobe claims that Flash runs on every platform ever, but as Chris Rawson astutely points out in this excellent article, that’s been easy to say while most of the world has been running Windows. With Apple’s laptops gaining popularity, people are starting to realize that Flash doesn’t run as well in OSX. The more Macbooks Apple sells, the more Adobe’s claims of market domination will start to dissolve.

No iPad/iPhone Support: take two — I want this website to be viewable on the iPhone, the iPad, and whatever whimsical hardware Apple comes up with next. That alone means I’m not going to use Flash in my blog’s design, ever. I’m admittedly in a minority here, but I wouldn’t be surprised if today’s kids getting into web design are also going to want to show off their cool, new, standards-compliant sites on their cool, new, iApproved devices. This sort of trend will slowly but surely push Flash out of the cool-new-site space.

Getting along with OSX is something that Adobe is going to have to work towards to keep Flash competitive, especially as new markets evolve out Apple’s hardware.

I’m not anti-Flash.

I’ve been using Flex Builder to build cutting-edge Flash applications for years, and I still believe there are many cases where Flash is a legitimate choice for creating a rich internet experience; there just aren’t as many as there used to be, and this combination of new, exciting technologies and pressure from Apple are making for some exciting times in the world of web design.

2010 is shaping up to be a wild ride for Flash and its competitors, and I can’t wait to see where it takes us. What are your predictions?