Saturday, February 5, 2011

Drawing in the lines



So I'm working on this really sweet HTML5 monster game, where you get to draw your own 8-bit style monsters and fight them against one another. So far I've only got a tiny bit of the monster creation part up and running. Don't worry I'll throw the whole thing up on on github when I'm done.

Anyway, one of the problems I ran into with the canvas was how to keep people's drawings within the predefined lines. The canvas is 500px wide and it's a 20x20 square of 25px blocks.

To create the lines it's very simple.

 ctx = document.getElementById('monster').getContext('2d');


 ctx.fillStyle = "black";
 for (i = 25; i < 500; i = i + 25) {
    ctx.fillRect (i, 0, 1, 500);
    ctx.fillRect (0, i, 500, 1);
 }

       That will draw some simple lines every 25px. Now how about keeping between the lines. It's simple. We just need to round our x, y to the nearest 25px, like so, that way it will always start inside one of our blocks. Then we'll actually be drawing 24px blocks to fit inside the lines completely.

I thought it was pretty neat!

        var draw = false;

 window.onmousedown(function() {
  draw = true;
 });

 window.onmouseup(function() {
  draw = false;
 });

 document.getElementById('monster').onmousemove(function(e) {
  var x = e.clientX - offsetX,
   y = e.clientY - offsetY;
   x = Math.round(x / 25) * 25 + 1;
   y = Math.round(y / 25) * 25 + 1;
  if (draw) ctx.fillRect(x, y, 24, 24); // keep things in the lines
 });


p.s. follow the progress over at http://www.jamund.com/monsters

No comments:

Post a Comment