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.


Notice: Array to string conversion in /var/www/joshemerson.co.uk/public_html/site/plugins/tags.php on line 22

Fatal error: Uncaught Error: Function name must be a string in /var/www/joshemerson.co.uk/public_html/site/plugins/tags.php:22 Stack trace: #0 /var/www/joshemerson.co.uk/public_html/site/templates/post.php(12): tags(Object(page)) #1 /var/www/joshemerson.co.uk/public_html/kirby/lib/template.php(36): require('/var/www/joshem...') #2 /var/www/joshemerson.co.uk/public_html/kirby/lib/template.php(25): tpl::loadFile('/var/www/joshem...', Array, true) #3 /var/www/joshemerson.co.uk/public_html/kirby/lib/site.php(203): tpl::load('post', Array, true) #4 /var/www/joshemerson.co.uk/public_html/kirby/system.php(65): site->load() #5 /var/www/joshemerson.co.uk/public_html/index.php(71): require_once('/var/www/joshem...') #6 {main} thrown in /var/www/joshemerson.co.uk/public_html/site/plugins/tags.php on line 22