Introducing drawpath

For the past three months, I’ve been working on creating in-browser games for Beamly, in my role as tech lead of the Games team.

For a simple game such as a quiz, nothing more than HTML and JavaScript are required, but when you want to make more interactive games, very often Canvas is the best choice.

The Canvas API lets you easily draw to the <canvas> element. Here’s an example of drawing a rectangle:

var canvas = document.getElementById('canvasEl');
var ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.rect(5, 5, 200, 100);

ctx.fillStyle = '#32E0B4';
ctx.fill();
ctx.lineWidth = 6;
ctx.strokeStyle = '#00D9A3';
ctx.stroke();

And here’s the outcome:

In the above example we drew a rectangle that was 200px by 100px and started at a point 5px from the left, and 5 px from the top. Now what about a triangle? Sure, here’s what you could write:

var canvas = document.getElementById('canvasEl');
var ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(5, 5);
ctx.lineTo(50, 50);
ctx.lineTo(5, 85);
ctx.closePath();

ctx.fillStyle = '#32E0B4';
ctx.fill();
ctx.lineWidth = 6;
ctx.strokeStyle = '#00D9A3';
ctx.stroke();

Ok, so far, so good. But what exactly do these points relate to, and how do you visualise them as shapes start to get more complex? I decided that I’d take the challenge of writing a simple Canvas JavaScript library that allows vectors to be drawn in the browser, and the Canvas code is then revealed to be copy-pasted. I call this drawpath. You can play around with it at http://joshje.github.io/drawpath/ or below.

Let me know how you get on with using drawpath. There’s plenty of features I want to add, not least of which the ability to edit the code and see changes in realtime, but for the time being it works as a simple path editor for Canvas.

Tagged:

Previous Post:

Webtastic Websites

It’s been an age since I’ve written a post on my blog. I’m going to break the habit and be updating it far more regularly.

My last post mentioned I was running some workshops in December. They went really well. Two intense one day workshops. At the end, the attendees learnt HTML and CSS, and managed to publish their first websites, all written from scratch!

Read more