Next page | Contents page |

Graphics

You have now worked your way through the Core Language part of this course. You probably found some of it quite dry. So you deserve some light relief.

The subject of graphics logically belongs at the end of the Document Object Model (DOM) section of the course but the results are interesting visually so let's do some now.

We covered most of what you need to know about the HTML5 <canvas> element, and the graphics context that can be programmed in JavaScript, in the introductory part of the course. (Review that.)

We did not cover putting text on a canvas. Now, that is something that should not be overdone: text in HTML pages really should be text, not part of an image. This is quite important for accessibility: visually impaired users may use a speaking browser and that cannot be expected to find text drawn into images. However, if you are drawing a diagram you may well want to label things in it.

The text capability of the graphics context is a more recent innovation than the rest of it, so current browsers may not support it. You need to start with a test in your code (after first checking that canvas itself is supported, as we saw earlier):


  function isCanvasTextSupported () 
  {
    var context = document.createElement ("canvas").getContext ("2d");
    return typeof context.fillText == "function";
  }

If it is available, fillText() has 3 parameters: the string followed by x and y. Eg, to label Alpha Ori in a star chart:


  context.filltext ("\u03b1 Ori", 57, 29); // Perhaps

The font and style are inherited from the CSS styles of the HTML <canvas> element for which this is the context. There are functions available for changing these.

Next page | Contents page |