Next page | Contents page |

Drawing graphics

The HTML part of this is very simple. Just create a rectangular area on which to draw:


  <canvas id="myCanvas" width="400" height="200">
    Alternative content, to show if the browser does not recognise canvas
  </canvas>

Units

The units for screen coordinates are pixels, the tiny physical picture dots on the screen. A computer screen will nowadays be at least about 1000 pixels wide and 800 high but a phone screen will of course be smaller.

[Update 2017: Phone screens can now have more pixels than computer displays. The final section of this course will show how to find out the screen size.]

Because computers used TV-like displays that scan down from the top left corner, that corner is (0, 0) and height is specified downwards. So if you are used to Cartesian (x, y) coordinates just flip them upside down for drawing on a computer screen.

In HTML you do not specify units but in CSS you must, using px for pixels.

All of the drawing on the canvas has to be done by JavaScript. We start in the usual way by getting a reference to the canvas element, of which there may be several on the page, so we use the relevant id:


var myCanvas = document.getElementById("myCanvas");

Every such canvas element in the DOM has something called a graphics context which does all the work, so the next step is to get hold of that:


  var g2 = myCanvas.getContext ("2d");

There are 2 important things to note here:

  1. The parameter "2d" allows for the possibility of other types of graphics contexts in future, such as 3-dimensional ones. For now always use "2d" as the parameter value.
  2. This invocation of the function getContext() will only work if the browser supports HTML canvas elements. So we can use this fact as a test of browser capability: does the function exist? Code it like this:
    
      if (!!document.createElement ("canvas").getContext)
      {
        var myCanvas = document.getElementById ("myCanvas");
        var g2 = myCanvas.getContext ("2d");
    
    The !! (double NOT) is a trick for ensuring that the result is interpreted as a boolean (ie, true/false) value. Also notice that the function name getContext is used here without parentheses after it: we are testing whether the function name exists, not calling the function. This is worth remembering as a general technique whenever we cannot be sure whether the browser will have a certain capability that we would like to use. If the test fails we might then provide alternative code.

Colors

JavaScript, HTML and CSS all use a special notation for specifying colours. It is a string beginning with # followed by 6 hexadecimal digits. The first 2 digits define the amount of red, the second 2 the amount of green and the last 2 the amount of blue. Colours on computer screens are additive combinations of those 3 colours (RGB).

Hexadecimal means that digits go from 0 to 9 and then A for 10, B for 11, and so on up to F for 15. Letter case has no significance. "Hex" is useful because 16 x 16 = 256 = 28, the range of possible values in one byte (8 bits).

So black is #000000 and white is #FFFFFF. Red is #FF0000. Yellow (red + green) is #FFFF00.

There is a convention that only 3 digits may be used if all 3 pairs are repeating digits. So #3C0 is short for #33CC00.

If the test succeeded and we have got hold of the context, in variable g2, there are then a large number of functions that we can use, belonging to the context object. For example, to draw a red rectangle with blue rim, with its top left corner at (100, 100), width 50 and height 40:


  g2.fillStyle = "#ff0000"; // red
  g2.fillRect (100, 100, 50, 40);
  g2.strokeStyle = "#0000ff"; // blue
  g2.strokeRect (100, 100, 50, 40);

Or to draw a green line consisting of a series of straight segments, build a "path" and then stroke it to draw it:


  g2.beginPath ();
  g2.moveTo (x1, y1);
  g2.lineTo (x2, y2);
  g2.lineTo (x3, y3);
  g2.strokeStyle = "#00ff00";
  g2.stroke ();

The context always keeps hold of one strokeStyle (line colour), one fillStyle (solid colour) and one path.

There is not a fillCircle() or strokeCircle() function. Instead you first need to construct a closed path as an arc going from 0 to 360 degrees (= 2.pi radians):


  g2.beginPath ();
  g2.arc (centreX, centreY, radius, 0, Math.PI * 2, false);
  g2.closePath ();
  g2.fillStyle = colour;
  g2.fill ();

Full details of the canvas element and how to program it can be found on the WHATWG site.

Examine the bouncing balls code from page 1 by looking at
bounce.js and
Ball.js

Interactive drawing application

If you want to see drawing in action we have written an example: grDraw. Use your browser to view the HTML source for that. You can also examine the JavaScript (and CSS) files used for it:
grDraw.js
grColourPicker.js
grDraw.css

The colour picker can give you practice in the # notation for colours.

Next page | Contents page |