Category Archives: Web Development

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

Google Chrome: Getting from dev channel to stable

As a developer, I tend to enjoy tinkering with the newest and shiniest of toys. Pretty pretty shiny shiny. Anyway, it turns out sometimes the newest and shiniest isn’t always so shiny and in fact is sometimes actually broken. Yes, I know that may come as a surprise to most of you, but indeed it is true. This actually happened to my Google Chrome recently on the dev channel with some broken page layout issues whenever I use page zoom, which these days is pretty much permanent. Wanting to keep Chrome as the default browser for several reasons, I decided I didn’t wanna be on the dev channel anymore. I reported the layout bug and set about finding my way back to the stable channel.

Boromir: One does not simply walk off the dev channel

The way to do this properly wasn’t really apparent from any Google searches I found – admittedly a very brief search, so I just decided to download the stable version of Chrome to see what happened. Worked, except I got this semi-cryptic error message:

Your profile can not be used because it is from a newer version of Google Chrome. Some features may be unavailable. Please specify a different profile directory or use a newer version of Chrome.

Yeah so how do you do that? Turns out it’s easily solved as discovered by searching on the error message text as I discovered on the Google Chrome Product Forum. Deleting the old profile works well enough if you are logged in to Google Chrome or don’t mind clobbering all your preferences and settings. The profile folder is found thusly:

  • Windows: %UserProfile%\Local Settings\Application Data\Google\Chrome\User Data\Default
  • Mac: ~/Library/Application Support/Google/Chrome/Default/
  • Linux: ~/.config/google-chrome/Default

Quit Chrome, delete the folder, launch your newly-installed stable version, log back in to Chrome, and you’re good to go.

TL; DR:

  1. Sign in to Chrome and make sure the preference to synchronize everything is turned on
  2. Download and install stable channel of Chrome
  3. Quit any running instances of Chrome
  4. Delete your profile folder
  5. Install and launch your stable version of Chrome
  6. Log back in to Chrome to get your settings back

Coloring the HR element line in CSS

I never, ever use this element, but HR has been bequeathed new life in HTML5 and I may start using it for providing more thematic break awesomeness to my already blindingly-awesome prose and poetry.

Anyway, someone asked me this question: Is color supported in all browsers by the HR element? To which I replied: “I have no clue. Let me investigate.”

Here’s an initial test:

Well hambone. Using the text rule for color on WebKit browsers yields no color change. Works fine in all cases in Firefox. IE gives no quarter to the border-color CSS property, but works fine with the text color value. Every browser supports HTML color attributes, but you know that using presentational markup is as wrong as Michelle Bachmann’s views on evolution and vaccination, so you just say no.

So what’s a poor web dev to do? Define a border width:

Replacing the original border-color rule with the shorthand listed here, or just providing an explicit border-width property, will render a consistent 2 pixel line in all browsers. If we just wrote something like border:thin solid red; we’d get a 2-pixel border – see you’d think the HR element is just a line, but in fact the browsers all treat it like a box it seems. So we have to clear it out with border:none; and then add a border-bottom or border-top rule to set a 1 pixel line. If you want different widths, you have arguably more accurate control by only having to argue with one border instead of two.

What… you want to replace that HR with a background image? Good idea. Check out this post at Neatly Sliced for the answer, and gird your loins for the usual IE kludgeries.

A quick book review: Responsive Web Design

Just finished reading an excellent book: “Responsive Web Design” by Ethan Marcotte. If you build web pages, I want you to read this book. Here’s a few of my thoughts on what I just learned, and why you should read this one too.

The book begins with an overview of the evolution of page layout in web design, starting with it’s roots in printed page design and moving on to today’s reality that there is a multitude of screens and devices out there, with more on the way. We cannot predict what type of device our readers will show up with, and must adjust our belief system (if we have one) to accommodate the new realities that the various screen widths and mobile device sizes present us with.

The second chapter discusses the idea of designing within the constraints of a flexible typographic grid. Grid systems are somewhat of an artificial constraint that designers place on themselves to provide balance and symmetry to page layout, and on screen a new challenge is presented in that the page size is no longer fixed. The main takeaway here is to design content in flexible porportions to the variable screen widths that might be used to access your web pages. Mr. Marcotte puts forth some simple, accessible ideas for developers to leverage, making text more readable on unknown devices by putting forth a formula that I’ll repeat here mostly for the purposes of getting my own head wrapped around it:

target ÷ context = result

To decode Mr. Marcotte’s example, he begins with an assumption of a base font size of 16px. The headline in the comp is defined to be 24px. So to make it flexible, divide:

24 ÷ 16 = 1.5

And so the headline should be defined as 1.5em. Simple and elegant rule of thumb. Now we just need to remember to do it.

Chapter 3 applies this principle to flexible images, and expands upon it. There is the inevitable Questionable Functionality Challenge™ presented to us by Internet Explorer, which is quickly defused. That’s a lot of ink to dedicate to an obsolete web browser and the example demonstrates where the real problem lies by showing how awful text looks in resized images. But you aren’t locking up text in your images, right? I know, I know, it’s an academic example and clearly illustrates the failings of IE’s image resize capabilities. Let’s move on.

Chapter 4 introduces media queries. We’re finally at what I consider to be the coolest and most important part of the book – how to progressively enhance your web page layouts through the media query construct. Mr. Marcotte makes the argument in favor of using the min-width property instead of things like max-width (which tends to yield excessive code) and min-device-width (which only pertains to devices and doesn’t take into account variable web browser windows.) The max-width property is introduced for those that want to stop the insanity. (I do know people that expand their web browser to the full width of their 27″ high resolution monitors.)

Chapter 5 pulls it all together with strategies to integrate responsive design into your team’s workflow; how to make your design process itself a responsive one. He builds the case for Luke Wroblewski‘s “Mobile First” philosophy (a case that was already built up a bit in chapter 1) and finishes it all of with how to incorporate progressive enhancement using JavaScript to selectively pull in a slideshow component only when JavaScript is available and all the stars are in the proper alignment.

Overall, my belief has always been somewhat of the philosophy that there should be just “one web”; no “mobile web” or any other sort of alternate web reality that we should somehow slip into. Today’s mobile devices that are in fact being used to access the web are billed as fully capable web browsing devices, and indeed they are. Why deliver a shrunken-down version of your website just because they have a 3″ wide screen these days? It no longer makes sense in most cases; just reposition your content to accommodate their view. Every chapter includes simple, usable techniques that work, and I feel that these gems of advice should be a core part your future projects.

Lastly, I am very thankful for the appearance of the A Book Apart series. Each one of these volumes is, I believe, how a tech book should be: concise, full of valuable, practical, actionable information. I have read several of these so far, and each one has been a hit. I look forward to more.

Annotate your Rails model

I just discovered this handy little gem called annotate. Run it and it’ll insert a comment in all of your model files at once, outlining the schema. This is incredibly convenient when working with your Rails models to be able to see the data and types right there in the top of the file.

Here’s what my Noober (/app/models/noober.rb) model looks like by default:

Spartan as always. Let’s give ourselves something to look at with the annotate command. First, include annotate in your Rails 3 project in the Gemfile:

Run the install command to update your gems:

Run it from within your project directory:

And the result should look something like this in your models:

Awesome! Now I can see quickly which parts of the model I need to work with and add my code without having to peek at the database:

Works well for me!