Tag Archives: standards

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

SVG and MathML in HTML5

The next article in the Developing with HTML5 series.

Pick a flower on Earth and you move the farthest star.

—Paul Dirac

Scalable Vector Graphics (SVG) and MathML are XML applications that are widely used in scientific contexts. SVG is used to draw vector graphics, and is frequently found in visualization libraries such as ProtoVis. MathML is used to describe the presentation and meaning of mathematical formulæ. They are very easy to work with in a programmatic sense, because they are XML-based and therefore just text, and yet they are capable of rendering beautiful information in supporting web browsers.

Paul Dirac, who loved the maths.
Paul Dirac, who loved the maths.

The idea behind XHTML was to move the web toward extensibility (the X in XHTML), where a web browser markup language could be seeded with bits of other XML applications by declaring a namespace and letting things coexist. The problem with that plan was that XML parsers were required to be extremely fussy, to the point that if a problem was detected the browser should render an error message. Browsers don’t work that way. Instead, they forgive your human or computer errors and render the page as best as their little hearts can.

In the beginning of the process, HTML5 was not extensible, and to this day it remains opposed to the whole namespace idea. But SVG and MathML are highly popular and useful XML applications that deserve a place within the HTML5 spec. And so shall it be: <svg> and <math> are the opening volleys in inserting SVG and MathML into your HTML5 document tree. Any elements that are children of the SVG and MathML specs are valid and functional child elements of the <svg> and <math> elements respectively. No need to declare a namespace. You’re done. Thank you.

Now this is not to say that the idea of inserting these XML applications within the HTML5 spec is not without some controversy. What about other XML applications and XHTML extensions such as RDFa, CML, and MML? CML (Chemical Markup Language) and MML (Music Markup Language) are indeed common, but within specific application contexts. They are not supported yet by any web browser (whereas MathML and SVG are well supported.) RDFa on the other hand is a more political issue: More on that whole mess in a later post… 😉

So in short, SVG and MathML are supported objects within HTML5 because they are widely deployed in existing web browsers, and they are very useful – particularly to those of us in the science industry charged with representing scientific information on the web. Let’s look at how to get started. First, an SVG example – simply start your SVG block using the <svg> element and drop your SVG markup within:

Here’s a live example that will work in browsers that support SVG and MathML in HTML5. (Try it in the Firefox 4 beta.) Or if you aren’t one of those early-adopting browser users that are used to living dangerously, then please refer to the perfectly safe reference image below:

Reference rendering of the sun in SVG.
Reference rendering of the sun in SVG.

To learn more about SVG, check out the w3schools SVG tutorial for starters. While SVG is supported in basic forms in Chrome, Safari, and Firefox, only Firefox 4 (currently in beta) supports embedding SVG natively in HTML5. But Chrome will follow soon, followed by IE9, Safari, and eventually (hopefully) Opera.

MathML is equally straightforward, using the <math> element as the opener:

Compare to the reference rendering below, or check out the live example.

The Dirac delta function rendered from MathML in Firefox 4 beta
The Dirac delta function rendered from MathML in Firefox 4 beta

Again, currently Firefox 4 beta is the only close-to-shipping browser that supports this. But it is expected to come to all major modern browsers in 2010/2011, including IE9, Safari, Opera, and Google Chrome. To learn more about how to construct MathML, check out Mathematica’s MathML tutorial.

In short, it’s an easy trip to embed SVG and MathML in HTML5. No namespaces are required. The trade-off is less extensibility, but if you need extensibility back there’s an XML flavor of HTML5, appropriately titled XHTML5. In the meantime, start looking for ways to leverage SVG and MathML in the coming months as capable browsers start coming online! While this is indeed a bit on the bleeding-edge side of things, web browsers are beginning to implement these features and I expect over the next year or two the practice of embedding SVG and MathML markup in HTML5 web pages will become entirely commonplace within the scientific community.

So close, and yet so far

Microsoft recently posted confirmation that their early builds of Internet Explorer 8 pass the Acid2 test for proper CSS rendering support. This was hailed as wonderful news among web developers worldwide as a momentus occasion where we could finally adhere to web development specifications as written and as intended.

Please Avoid Carefully The Collision

And then came the big let-down.

In a more recent post, Microsoft announced that in order to have IE8 enter true standards mode, you’d have to enter an extra HTML meta tag. An extra, non-semantic, content-free, crufty, browser-specific meta tag. As if this were some parting shot – some way of saying (in your best Joe Pesci “Goodfellas” voice:) “Oh yeah you want standards mode? I got your standards mode right here baby! Yeah….”

I read that announcement and felt deflated. I tried to rationalize it, saying hey – at least we know that there is some otherworldly way to get IE to behave to spec finally – but then the rationalist in me ultimately won out and rejected this categorically bad idea. This is wrong on many levels:

  1. This penalizes web developers who have been striving to adhere to web standards and do the right thing, while rewarding bad behavior.
  2. This inserts yet another rendering mode. How many rendering modes do we need to support? Will there be more?
  3. This inserts the idea of targeting browsers with versioning. Future browsers. Not past browsers. This sets up the case for decades of cruft and bloated code.
  4. This added tag will ultimately mean many terabytes of added bandwidth and added disk space. Good for vendors, bad for you.
  5. Already-standards-compliant Firefox, Opera, and Safari are doing just fine and increasing their market share while IE wanes.

I stopped at 5, but if you read the comments to the post over at the IE blog, you’ll find many more. If you really feel the need to provide backwards compatibility to all those sites who were trying their best but still had to hack otherwise standards-compliant sites up to get them to work properly in IE 6 and 7, then give them the meta tag option. I’ll wager the few who care and would rather insert this meta tag over coding their web sites to spec will be happy, and the lions share of web site owners out there won’t have a care in the world if it works or not. Because let’s admit it: Most of them will have moved on by the time IE8 matters.

Researching web information architecture, usability, and standards

If you are a web developer, web designer, web architect, web usability expert, in a similar role, or just have an opinion on the subjects of web architecture, usability, and standards, I need your help! I am doing a research paper on the arguments in favor of having large enterprise organizations develop policies for the following issues:

  • Implementing and enforcing a standardized user interface for an enterprise web presence.
  • Developing an enterprise web information architecture.
  • Developing and enforcing a web style guide.
  • Enforcing web standards (i.e. valid XHTML, CSS, DOM scripting using ECMAScript standard, etc.
  • Usability and accessibility issues (Section 508, case law, etc.)

Broad category? Yes. But hey, it’s easier than writing about how to curb global population growth or global warming. I’m trying to positively influence the world through better enterprise web strategy. My goal is to bring standards-based web design out of the sidelines and fully into the mainstream at the enterprise level. I think the case has been made clear for small web infrastructures and web 2.0 plays, but the enterprise still lags in this area and it is a far more challenging problem due to the information and organizational complexity of such behemoths.

I need your help! If you have any suggestions, opinions, recommended books, citations, essays, or good URLs to post, please let me know in the comments! Any opinion on this topic is welcome.

Thanks!