Canvas experiment 1: OGD logo

1 minute read

Using the Canvas API you can easily draw shapes, text and other graphics on web pages, using only HTML and some JavaScript. The next couple of weeks I’ll experiment with Canvas and publish a new blog post every weekend.

How does it work?

I created a couple of base HTML and CSS files so that I don’t have to start from scratch every time I want to play with canvas. They’re really basic and can be found right here on github.

The OGD logo contains six elements: the texts ‘OGD’, ‘ict-diensten’, ‘samen slimmer’, the red line and the two red shapes at the top left. Also, the entire thing is rotated about 20 degrees.

First I’m going to draw the text. This is easy enough using only two functions: context.font to set the font and context.fillText to draw the text. The colour is set using the fillStyle property.

function drawText() {
   context.fillStyle = '#6C276A';

   // OGD
   context.font = 'bold 164px ogd';
   context.fillText('OGD', OFFSET_X, OFFSET_Y);

   // ict-diensten
   context.font = 'bold 60px ogd';
   context.fillText('ict-diensten', OFFSET_X + 70, OFFSET_Y + 70);

   // samen slimmer
   context.font = 'italic normal 50px ogd';
   context.fillText('samen slimmer', OFFSET_X + 70, OFFSET_Y + 160);
}

Now that the text is drawn, I create the three other shapes using moveTo and lineTo. They are then drawn to the canvas using either fill or stroke.

// triangle left
context.beginPath();
context.moveTo(OFFSET_X - 160, OFFSET_Y - 100);
context.lineTo(OFFSET_X - 110, OFFSET_Y - 50);
context.lineTo(OFFSET_X - 160, OFFSET_Y);
context.fill();

// shape right
context.beginPath();
context.moveTo(OFFSET_X - 50, OFFSET_Y - 100);  // top right
context.lineTo(OFFSET_X - 50, OFFSET_Y);        // bottom right
context.lineTo(OFFSET_X - 125, OFFSET_Y);       // bottom left
context.lineTo(OFFSET_X - 75, OFFSET_Y - 50);   // center
context.lineTo(OFFSET_X - 125, OFFSET_Y - 100); // top left
context.fill();

// line
context.lineWidth = 3;
context.beginPath();
context.moveTo(OFFSET_X + 70, OFFSET_Y + 115);
context.lineTo(OFFSET_X + 380, OFFSET_Y + 115);
context.stroke();

End result

The final thing is embedded below. Click the OGD logo to make it rotate. Click again to stop. Note that I used some ES2015, which will only work if you use an up-to-date browser (IE users: 11 or Edge). You can view more on CodePen or browse the code on github.

Updated: