Category Archives: Graphic Design

A quick introduction to the HTML5 Canvas

The next article in the Developing with HTML5 series. Better late than never, but much has happened. Perhaps more on that someday…

A painter paints his pictures on canvas. But musicians paint their pictures on silence. We provide the music, and you provide the silence.

—Leopold Stokowski

HTML5’s canvas element allows us to create and display images on-the-fly using JavaScript. Canvas graphics can often yield speedy performance, particularly on mobile devices and desktops that feature browsers with hardware acceleration enabled. While SVG (which I covered earlier) does feature a convenient model for markup and CSS access to the graphic in question, Canvas can usually do a better job at performance thanks to hardware acceleration and not having to traverse the DOM.

Let’s analyze a basic canvas. Start with a new HTML5 document containing a canvas element in the body:

Save your file. Not much will happen yet, unless you have web browser that doesn’t support canvas. Modern browsers will probably yield a blank white page for the above code. An older non-supporting browser, a text-only browser such as Lynx, or a screen reader will deliver the default text:

Lynx renders default text for canvas

You can draw on the canvas using JavaScript. Place this code above the closing element to try it out:

Now when we preview our page in a supporting browser, we should see a green box:

Green canvas box

To explain what we did with this JavaScript: We wrote a function called draw(), which first uses the d ocument.getElementById() method to grab our #example canvas element. The next line sets the rendering context with canvas.getContext(). We then use the fillStyle() method to assign a CSS color value and the fillRect() method to draw the box.

The prototype for fillRect() is fillRect(x, y, width, height). The x and y values position the box relative to the bounds of the canvas, and the
box is drawn from there using width and height.

Now let’s try a circle. (And throw in some alpha transparency for good measure.) Add five more lines to our ctx variable as shown:

The result should be an overlapping circle

Progress of canvas showing circle overlapping rectangle

Here, we’ve used the fillStyle() element to define a light violet color for our circle. You’ll notice that this time we are passing in one extra number to fillStyle(). That extra number is a parameter that sets the alpha transparency—any decimal value from 0 to 1 is valid, with 0 being fully transparent and 1 being fully opaque.

In this case, our value of 0.5 might be thought of as a 50% transparency. We see the true violet color of our circle along the right edge where it hangs off of our green square, and we see a blend of the two colors (which happens to be a neutral gray) where the two shapes overlap.

Because we want to create a circle instead of a square in this example, we need to use the beginPath() and closePath() methods to draw a linear shape. We use the arc() method for defining the path itself. The first two values in the arc() arguments are x and y coordinates within the canvas. Third is the arc radius, which here is set to 75 pixels. The last two values are the start angle and end angle. We can specify a calculation for these angles, so here we set our end angle by leveraging JavaScript’s built-in Math object to multiply pi by 2.

Now let’s add a regular jpeg image to our canvas after our circle (below the last ctx.fill() line):

piano keys closeupThis adds our piano image (shown here—please feel free to download for use with this tutorial) to the canvas. Above, we begin by initializing a new instance of the Image object. The src property specifies the path to our image (which may be relative or absolute). Next, the onload property tells the canvas to execute the drawImage() method, specifying our piano image as the source and x and y coordinates of 30 pixels each.

But why is that special? After all, we could have just inserted an <img> tag there, right? Yeah, but since this is JavaScript, we can clone it. Here’s how to add another instance of the image using different parameters:

We’ve resized our cloned image, too. (It’s now 70 pixels square.) And now we can apply effects to it. How about trying a little drop shadow?

Here’s our finished masterpiece:

A rectangle, circle and two copies of a piano keyboard image composed onto the HTML5 canvas

And that is what modern art is all about. Here’s our final code example:

This is just the tip of the iceberg—but it should be enough to show how to get a basic canvas working in HTML5.

The canvas element is fairly well supported on modern versions of most web browsers, including Firefox, Safari, Chrome, and Opera. This goes as well for their mobile equivalents, with the exception that the Text API for canvas has spotty support for Opera Mini.

Internet Explorer 9 even includes support for the canvas element. For older versions of IE, add Explorercanvas as a source to your web page and you’ll achieve pretty good compatibility out of the box. You can check current browser support for canvas features on caniuse.com

Dogs and cats, living together. Mass hysteria.

Wha?

There has always been somewhat of a dichotomy in the world of web professionals between design & development.

Designers do their thing making pretty pictures, drinking cocktails at lunch, having social cliques, and little romances within the group. They frolic away in the meadows of Photoshop and Dreamweaver Design View, paying little attention to the nuances of the mechanical underpinnings of their creations. Or so I hear…

Meanwhile, the code monkeys toil away in the dark, unseen from the public eye, in caverns and closets and in back alleys where you dare not travel. Typically found unshaven in the wild, they hack away in text editors such as TextMate and Vim, write their code from scratch, and make jokes about algorithms in C in an Erkel-esque voice from behind Coke-bottle glasses. (Mexican Coke bottles, since apparently north of the border we’ve lost our flair for nostalgia and authenticity and now mostly distribute the plastic bottles which are unfit for ocular correction.)

I’ve had this debate at least six or seven times in my career, in some form or other, about this separation of church and state. Oil and water. Dogs and cats.

Stephanie Sullivan recently wrote this:

The root of my story and my point is — it’s the rare individual that has all the strengths needed for one web site. It’s the team that matters. Should everyone have a basic understanding of the other member’s jobs? How they work? What they can accomplish. Oh yes. Absolutely. Should they be able to do them? That’s just ludicrous. Absolutely not. Surround yourself with people more brilliant than yourself. Always learn. Work hard. You, and those around you, will be enormously successful.

Now granted, she’s posting this in response to the guys at 37signals, who by definition are an opinionated group making opinionated software. That’s why their stuff is so great – they set some constraints and they live by ’em. I’m not sure which posts she was referring to, but this could be one of ’em. And this is true. Designers who have strong developer kung fu are better designers for it. And developers who understand the issues of design are correspondingly empowered.

But I tend to agree with Stephanie. The reality of it is that there are a wide variety of personality types out there, and that translates into varying abilities and motivations for crossing over into the design or development realms one way or another. As a musician, I myself come from a deeply creative side (with some early code hacking expertise in the Atari days,) but have come around to being mostly a developer at this point in my career. I draw heavily on my design background when working today. But I certainly would want to get a good, web-experienced designer on my project. And I think that’s where the core of the debate has led to: Web designers who understand The Code create designs that make better sense within the constraints of the digital medium, and understand what the user interface objects are that the web-surfing masses are familiar with. Conversely, pencil-necked code monkeys understanding design principles won’t shackle their creations with masses of cruft and flotsam just because it worked 9 years ago and why not copy/paste that in?

There are so many faceted roles now applied to the web production line. We are all part designer, part coder, part marketing stooge, part librarian. There is no escaping that. But if the Industrial Revolution has taught us anything, it is that things will continue to specialize in the name of efficiency and progress. Multitasking sucks. For some of us (moi,) it sucks more than for others. It takes time for the brain to switch gears between the too-sexy-for-my-shirt design aesthete and the l33t h4x0r. Throw having to be a project manager, writer, or manager into the mix and you get all kinds of crazy flying around.

My take on it all is: Embrace what you are good at. Do what your passion dictates. Challenge yourself frequently, but never lose sight of your foundation. If your foundation migrates, then great! But always be aware of yourself and live in The Now™. If you do what you love, you are more likely to get good at it, more likely to stick with it for the long term, and good things will tend rise up around you.

Judging a book by it’s cover…

Sharks patrol these waters...

Or in this case, judging a candidate by their web design! Let’s face it – I am no political wag, and politics is something best left to other demagogues and zealotous pundits across the spectrum.

However, I can claim passable knowledge in double bass, and claim a rudimentary knowledge of web development design and development practices. Obviously I certainly can’t use my bass chops to judge this year’s candidates for president, although if one were to bust out a contrabass and wail out a rendition of oh, say the Koussevitsky Concerto in solo tuning, then I’d have vote for them just on principle.

But I sure as hell can embrace my inner fashion slave and get all up in their web design business! If nothing else, I can at least engage in the purely superficial practice of candidate analysis by using their primary online web presences as the basis:

  • http://www.barackobama.com/ – PHP backend, which says to me: “I’m an open format, flexible, and I like to get things done.” Title tag reads “Barack Obama | Change we can believe in.” Great design, usable. Very ‘web 2.0’-ish design. What stands out: Quote that says “I’M ASKING YOU TO BELIEVE. Not just in my ability to bring about real change in Washington… I’m asking you to believe in yours.” First line of quote in all caps which we will see is overused later on, but here provides appropriate emphasis in the context of the quotation. While I generally don’t like to see drop-down primary navigation menus, these are done well and seem to server the text that is within. Only criticism is the most recent blog post in which they inserted 14 full-size images that were subsequently shrunken down in the display using HTML attributes. This is generally considered a bad idea. Please cut them down to an appropriate pixel dimension for the thumbnail versions and link back to the high-resolution copies. But that is more of a content management issue…
  • http://www.hillaryclinton.com/ – ASP.NET, with a slightly disturbing marionette-like picture of Hillary, and the words in bold “MAKE HISTORY.” In all caps. For emphasis I suppose. Kind of a weak message if you ask me. It’s saying: “Vote for me, just because I’ll be the first woman president.” Drop-down menus seem a bit boxy and compartmentalized – I don’t find them to be as readable as Obama’s. Update: I check back the next day to find that they updated Hillary’s site with a new, vastly improved photo. Airbrush is your friend. Seriously – I have no problem with the airbrush tool in Photoshop and intend to wipe away each wrinkle in my own photo history as they occur…
  • http://www.johnedwards.com/ – Appears to be static HTML. Design looks dated. Message says “Thank You, South Carolina.” Color theme is not your typical palette. Here we have a sort of ochre/green/maroon/blue thing going on – a wider gamut than your usual red, white and blue political site.
  • http://www.johnmccain.com/ – Running on an IIS server. Interestingly, trying any file extension other than .aspx yields the default IIS 404 error page, but when using a .aspx, we get the “intended” 404 page with the site chrome. Noticed this problem on Hillary’s site too. I’m a fan of monochrome color schemes, so I had a soft spot for the site when I hit their splash page. (Why do all these sites insist, in 2008, on using splash pages still?) But the soft spot faded quick when I came to the home page and got overwhelmed with boxes, sliding pictures, a scattering of instances of “click here!” and “learn more” buttons, and a giant smiling McCain holding a mic. Message: “Best Prepared to Lead on Day One.” (Using smallcaps, for slightly less emphasis than all caps I suppose.) But for a minute I thought the site message was “click here.” This page has some nice b/w treatment. Overall I find this site to have an overabundance of head shots – maybe scale it back 50% or so? I get saturated by it – front, left side, right side, repeat.
  • http://www.mittromney.com/ – Server is running Apache Tomcat and appears to be servlet-driven. Slogan: TRUE STRENGTH FOR AMERICA’S FUTURE. You alpha male you. Center image advertises “Limited Edition Mitt Romney T-Shirt Designs” that suspiciously look like André has a Posse stencils. Right action box has the heading “TEAM MITT,” which I subconsciously took to read “dammit” for a minute there. Like the Five Brothers section overall, although they really need a sharper JPEG for the banner.
  • http://www.mikehuckabee.com/ – IIS server. Same 404 problem as McCain and Clinton. Not sure why this is hard on Microsoft web servers – should not all not found pages get the same treatment. Site uses Scriptaculous and Prototype, although I didn’t see any use of these in my cursory glance. Overall not a bad design. Oops – just saw the tagline in the right banner: “FAITH. FAMILY. FREEDOM.” I smell erosion of the 1st amendment separation of church and state and must flee far away from this site…
  • http://www.joinrudy2008.com/ – PHP, and overall not a bad site design. His site doesn’t use his first and last name. The site rudygiuliani.com appears to be controlled by a domain squatter. Anyway, the home page renders an embedded Flash video with Rudy’s portrait in the still image, and I’m immediately reminded of something: Rudy looks like a mortician from one of those wild west flicks – the gaunt, hunchbacked undertaker in a long coat and stove-pipe hat. By now I’ve noticed the ubiquitous box in the lower right of each candidate’s home page that is used for linking to their MySpace, Flickr, Facebook, Digg, and whatever presences. Looking at the home page, I don’t immediately have a message to take away. Every other candidate seemed to have one engraved in text somehow. I was shocked there was no typographical mention of 9/11 mentioned. To get Rudy’s message, you need Flash and have to run the home page video (a feature he relies upon site-wide). OK, once we run this, I see the familiar harping on terrorists and 9/11 that we all know and love from Rudy’s talking points. Rudy’s blog is all video posts, which is kind of odd and probably not that friendly to search engines or people scanning for messages.
  • http://www.ronpaul2008.com/ – PHP, and not a bad first impression for the site design. In fact, we get a meta tag generator attribute that tells us they use Moon PHP MVC framework. Has a Web 2.0 feel to it, although we feel a bit cluttered on the home page. Ron’s tagline is “HOPE FOR AMERICA.” Glad to see at least one candidate on the Republican side has moved beyond wrapping themselves in a flag and thumping on a bible. Join Campaign page has appropriate use of fieldsets which is a nice touch. But what’s this? Under the “The issues that most concern me in this election are:” fieldset, we have a checkbox entitled “Pro-Life.” Obviously this campaign is prepared to exclude the pro-choice camp from having a voice here. Pro-life is not an issue, it is a position on an issue.

Well that was an eye-opener. It is mind-numbing when you have to pay attention to these wingnuts for only a few minutes. It is interesting to note the similarities between many of the sites – the general layout, the features they all place in their sites and on the home page, and how they treat color and typography. The quality of the various sites overall was good, but not really that great. I have to say, for my tastes Obama’s site is by far the best of the crop. The design is there, the usability is there, it nails the design trends of 2007 on into the present, and has the best treatment for features, typography, and messaging. On the Republican side, I have to say that Ron Paul’s site is best, but I’m still having trouble getting past the semantics for that one checkbox issue. Of the three main democratic candidates, I noticed a sense of overall inclusion and positive attitude. On the Republican side, with the exception of Paul’s and somewhat on Romney’s site, I got the feeling that they were trying to convey a sense of “this is what we believe and how we’re going to do things – end of discussion.”

Interestingly, I was surprised to see that all of the ASP.NET/IIS websites failed to have a good 404 error page behavior. And overall, the PHP sites seemed to be coupled with the highest-quality page designs and content structures, although correlation does not equal causation as the whole pirate to global warming trend so effectively illustrates.

Clobber and rewrite

It’s time to redesign. I’ll use my traditional method of blowing everything away and starting from scratch.

Also upgraded to WordPress 2.3 today. Noticed some of my categories are missing. This is a first for me – usually the upgrades go pretty well.

I wonder what design I’ll come up with…

I also need to find a new web host.

So pardon the dust. This is a work in progress.