Line art with an HTML5 canvas

Let’s play with HTML5 canvas elements!

Basically, I want to draw some simple line diagrams. Go from top to bottom on one side while going from right to left along the top or bottom. It sounds complicated, but perhaps it’s easier to explain with a drawing:

The code for that is actually surprisingly simple:

jQuery(function($) {
  var c = $("#canvas0")[0].getContext('2d');
  var w = $("#canvas0").width();
  var h = $("#canvas0").height();

  c.lineWidth = 1;
  c.strokeStyle = col;

  c.beginPath();
  for (var i = 0; i <= d; i++) {
    c.moveTo(0, i * h / d);
    c.lineTo(w - i * w / d, 0);
  }
  c.stroke();
}

That was easy enough, but what if we want to generalize out to something more like these:

What additional variables do we want? It would be nice to be able to draw how many lines we’re going to use, the rectangle we’re drawing in (x, y, width, height), the color of the line, and the orientation. Combine all of that and you have something like this:

function drawGrid(id, x, y, w, h, d, col, which) {
  var c = $("#canvas")[0].getContext('2d');

  c.lineWidth = 1;
  c.strokeStyle = col;

  c.beginPath();
  for (var i = 0; i <= d; i++) {
    if (which == "tl") {
  	  c.moveTo(x, y + i * h / d);
	  c.lineTo(x + w - i * w / d, y);
    } else if (which == "tr") {
	  c.moveTo(x + w, y + i * h / d);
	  c.lineTo(x + i * w / d, y + 0);
    } else if (which == "bl") {
	  c.moveTo(x, y + i * h / d);
	  c.lineTo(x + i * w / d, y + h);
    } else if (which == "br") {
	  c.moveTo(x + w, y + i * h / d);
	  c.lineTo(x + w - i * w / d, y + h);
    }
  }
  c.stroke();
}

Here is the source for the more complicated images:

// outer border
drawGrid("#canvas1", 0, 0, 100, 100, 25, "green", "tl");
drawGrid("#canvas1", 100, 0, 100, 100, 25, "blue", "tr");
drawGrid("#canvas1", 0, 100, 100, 100, 25, "green", "bl");
drawGrid("#canvas1", 100, 100, 100, 100, 25, "blue", "br");

// inner border
drawGrid("#canvas2", 0, 0, 100, 100, 25, "red", "br");
drawGrid("#canvas2", 100, 0, 100, 100, 25, "green", "bl");
drawGrid("#canvas2", 0, 100, 100, 100, 25, "blue", "tr");
drawGrid("#canvas2", 100, 100, 100, 100, 25, "black", "tl");

Now the fun part, you can play with the settings:

left
top
width
height
lines
color
corner

If you’d like to download the source, you can do so here: html5-line-art