Tag Archives: science

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.

Create the change you want to see in the world, one environment at a time

Today I came across this article from Peter Bregman on the HarvardBusiness.org site, titled: The Easiest Way to Change People’s Behavior. It’s an excellent read and highly recommended.

What Peter discusses in this article is that one of the most important motivational factors in our lives is environment. If you put the right things in front of you, you’ll tend to use them more. Move them away, and they’ll get used less.

This goes for good things as well as bad things. On the positive side, consider proximity of the things that are beneficial: The gym is only a block away, so you go regularly. If the gym is far, you don’t go. Some examples based on the article:

  • Use a bigger spoon or plate, and you eat more. Use smaller ones and you eat less.
  • Live near a liquor store or a Burger King and people tend to drink more and eat more junk food. Place yourselves farther away from those and you tend not to indulge in such sins.
  • For musicians, keep your instrument and music in an area where you’ll most likely use it. Designate a practice area and have your instrument either out of it’s case or put the case in an easily accessible area. Music on the stand. Metronome on the desk. Ready to go. (I personally have found having a tuner (iStrobeSoft) and metronome (Dr Betotte TC) on my iPhone to be one of the biggest music practice productivity boosts yet. No searching for gadgets…)
  • Want kids to do their homework? Give them a clean, organized place to do it and make sure the homework is there and not floating around the house in some random place. (I know this from experience…)

In a Web 2.0 context, this equates to the usability of your software. Make it easy for your users to get things done, and they’ll do it without a hitch. Throw up roadblocks, and they’ll get stuck. It doesn’t matter how small the roadblock is or whether or not the construct was well intentioned or not – if it impedes usability, then it will impede usability. 😉

In a greater sense, there’s a lesson for the nation or the world: If you want people to change the way they are doing things, make them want to do it. Make it easy for them. Remove any and all barriers to getting things done. You want people to vote? Put voting booths in more neighborhoods or promote the option to vote by mail. Need people to get immunized? Set up neighborhood clinics. Want your employees to be more productive? Find out what is it about your office environment that is getting in the way or not helping promote the results you want to see. For kids, for employees, for citizens, provide the right environment and make it a place they want to be.

Doctor Atomic

Doctor AtomicI saw the San Francisco Opera perform Doctor Atomic last night. My opinion: It was amazing, and this is one for the ages.

Now first off, let’s get the criticism out of the way: There were a couple of spots that just dragged on nebulously, and I started to just get plain old bored. It is very hard to get me bored at an opera ��� I love opera performances, and especially this one for me had given me a lot of anticipation. Specifically, I’m referring to Scene II, and just a little bit from Scene III.

However, this is a relatively minor critique in light of the overall composition, production, and performance.

Kristine Jepson as Kitty Oppenheimer was absolutely amazing. Her impressive vocal execution of some incredibly difficult passages was my favorite part of the vocal component of this opera. All the vocal performances were great, including the chorus, and I really enjoyed it.

The production, especially the set design and choreography, made a real impression on me. The visual sight of a mother and child alone on a dark stage, with an enormous bomb hanging right over their heads, while sounds of everyday conversation was looped via tape. The choreography was spectacular in the way it depicted the concepts of everyday work juxtaposed with the horror of war, all underlined by the physics of the atom.

Segments of the text were direct copies of things I recognized, from the letter by Leo Slizard to initiate the Manhattan Project, to Oppenheimer’s recitals of ancient Sanskrit from the Bhagavad Gita. (I may have missed it, but I don’t think that they worked in his famous and ominous recitation of the phrase from chapter 11 of the Bhagavad Gita before the Trinity test: I have become Death, Destroyer of Worlds.)

This was an opera about deep personal conflict, revolving around the genius Oppenheimer and his colleagues as they proceeded to build the greatest weapon of mass destruction ever conceived. To invent a conventional weapon is one thing. But to invent a weapon that is capable of erasing the lives of hundreds of thousands of people in one instant, that is something that generates feelings of unimaginable horror, extreme guilt, and even inescapable fascination. What really left me after seeing this opera was the take on the issues involved: The conflict, the humanity, the despair, the fear, and the human curiosity and determination that saw it all through in the face of everything.

The opera ended with the test blast at the Trinity site, with everyone’s heads propped up from their positions of shelter in fascination and awe. As the rumble subsided, a Japanese woman’s voice can be heard repeating over and over again a simple request for a drink of water. This is an ominous reminder of the horrible aftermath of what happened in Hiroshima and Nagasaki, where the water was heavily tainted so that those that drank the water suffered and died from radiation poisoning, while those that did not drink suffered and died from thirst ��� and more importantly ��� a reminder that war’s greatest tragedy is how it affects the innocent.

I am especially glad that I got to see this opera in it’s premiere. I can tell that this one will go down in history as one of the top operatic works of our era. It is a work of genius, and I do not use that word lightly.

I think that this opera goes right on up there with Minard’s chart of Napoleon’s campaign in Russia as some of the most effective anti-war propaganda ever created.