Showing posts with label canvas. Show all posts
Showing posts with label canvas. Show all posts

Wednesday, September 18, 2013

Testing Canvas in Dart


While working through some of the later chapters in Dart for Hipsters, I found some code that really was not tested. Better yet, I know why it is untested: I don't know how. Yay! Fresh earth.

The Dart code in question is part of a whirlwind tour at the end of the book. Specifically, I have a very simple canvas demonstration:



The code draws a simple square, fills it, and attaches keyboard handlers to move the square around the screen. I already know that I cannot test the keyboard events. At least not yet. But I can still test something. In fact, if I had been testing, or at least performing simple code analysis, I would have noticed that I still have the old-style on.keyDown.add() event handling:
  document.
    on.
    keyDown.
    add((event) {
      String direction;

      // Listen for arrow keys
      if (event.keyCode == 37) direction = 'left';
      if (event.keyCode == 38) direction = 'up';
      if (event.keyCode == 39) direction = 'right';
      if (event.keyCode == 40) direction = 'down';
      // ...
    });
I get everything working by switching to the new stream-based event handling:
  document.
    onKeyDown.
    listen((event) { /* ... */ });
But I have nothing in place to prevent regressions should the language continue to evolve.

This turns out to be fairly easy with Dart's unittest:
import 'package:unittest/unittest.dart';
import 'dart:html';

import '../web/main.dart' as Canvas;

main () {
  group("[canvas]", (){
    var canvas;

    setUp((){
      canvas = new CanvasElement();
      document.body.append(canvas);
    });

    tearDown(()=> canvas.remove());

    test("code runs", (){
      expect(Canvas.main, returnsNormally);
    });
  });
}
Here, I import the main.dart entry point for my canvas experiment and manually run the main() entry point function—expecting it to return normally. A bit of setup is required to add an expected <canvas> tag (along with matching teardown code). But really, very little is required for a pretty useful test.

It even works from the command-line thanks to the magic of Chrome's content_shell:
➜  code git:(master) ✗ content_shell --dump-render-tree index.html
CONSOLE MESSAGE: unittest-suite-wait-for-done
CONSOLE MESSAGE: PASS: [canvas] code runs
CONSOLE MESSAGE: 
CONSOLE MESSAGE: All 1 tests passed.
If I intentionally break the code (by reverting my stream fix), I get the failure that would have helped me earlier:
➜  code git:(master) ✗ content_shell --dump-render-tree index.html
CONSOLE MESSAGE: unittest-suite-wait-for-done
CONSOLE MESSAGE: FAIL: [canvas] code runs
  Expected: return normally
    Actual: <Closure: () => dynamic from Function 'main': static.>
     Which: threw NoSuchMethodError:<Class 'Events' has no instance getter 'keyDown'.

  NoSuchMethodError : method not found: 'keyDown'
  Receiver: Instance of 'Events'
  Arguments: []>

  package:unittest/src/simple_configuration.dart 140:7
  package:unittest/src/simple_configuration.dart 15:28
  package:unittest/src/expect.dart 117:9
  package:unittest/src/expect.dart 75:29
  ../html5/test/test.dart 20:13
My code event passes type analysis, which I perform automatically on any tested code in the book with dartanalyzer in my test_runner.sh:
# ...
# Static type analysis
echo
echo "Static type analysis..."

results=$(dartanalyzer test.dart 2>&1)
echo "$results"
if [[ "$results" == *"[error]"* ]]
then
    exit 1
fi
# ...
That is all well and good, but is it possible to test some of the innards of the <canvas> element after the initial screen is drawn by main()? As can be seen from the screenshot above, the “player” starts near the top-left of the screen. In fact, the default is specified in the Player constructor:
class Player {
  int x, y;
  int width = 20, height = 20;
  Player() {
    x = width~/2;
    y = height~/2;
  }
  // ...
}
The x-y origin of the starting position is then (20/2, 20/2), or (10, 10). Given that the width and height of the box is 20×20, the box ends at (30, 30). Since the “player” box is the last thing drawn in the <canvas> element, I can have an expectation that the point (30, 30) is in the current path:
    test("player is drawn", (){
      Canvas.main();
      var context = canvas.getContext('2d');
      expect(context.isPointInPath(30, 30), isTrue);
    });
And that passes!
PASS: [canvas] player is drawn 
If I change the expectation to (31, 31), my test fails:
FAIL: [canvas] player is drawn
  Expected: true
    Actual: <false>
So not only do I have a test that will catch small changes in the language that might affect my <canvas> code, I also have a test that will verify that my drawing works properly. And it even works from the command line.


Day #878

Sunday, March 11, 2012

Getting Started with Dart Canvas

‹prev | My Chain | next›

Tonight I am going to start playing with Canvas in Dart. I much prefer something like Rapahaël for doing Canvas things in Javascript. Still raw Canvas can be useful as times as well. I am basing this off of a post that I did back in 2010 on Canvas.

I start with an HTML page empty except for a title, a script tag to pull in my main.dart file, and a little Javascript kick start that is still necessary to get the Dart engine humming in Dartium:
<html>
<head>
  <title>Hipster Canvas</title>
  <script type="application/dart"
     src="main.dart"></script>

  <script type="text/javascript">
    // start Dart
    navigator.webkitStartDart();
  </script>
</head>

<body>
<h1>Oooh Canvas!</h1>

</body>
</html>
To add the Canvas element, I try:
// Neither of these work...
new CanvasElement();
new CanvasElement.html('<canvas/>');
It seems, however that only Element.html() works as a constructor (sub-classes are not blessed with this ability). So, my main.dart becomes:
#import("dart:html");

main() {
  var canvas = new Element.html('<canvas/>');
  canvas.width = 900;
  canvas.height = 450;

  document.
    body.
    nodes.
    add(canvas);
}
With that, I have a canvas:


I move the canvas initialization into its own buildCanvas() function and would now like to set about drawing my avatar on the canvas:
CanvasRenderingContext context;

int width = 900,
    height = 450;

main() {
  CanvasElement canvas = buildCanvas();
  context = canvas.getContext("2d");
  draw(x: (width/2).toInt(), y: (height/2).toInt());
}
I grab the rendering context from the canvas and squirrel it away in a library-wide variable, context. I also store the width and height in library-wide variables so that I can draw myself at the exact center of my canvas universe. I lack subtlety.

As for drawing myself, for now I will be simply a red rectangle. First, I wipe the canvas clean, then draw myself in the appropriate spot:
draw([int x, int y]) {
  context.beginPath();

  // clear drawing area
  context.clearRect(0,0,width,height);
  context.fillStyle = '#ffffff';
  context.strokeStyle = '#000000';
  context.fillRect(0,0,width,height);

  // draw me and fill me in
  context.rect(x,y,20,20);

  context.fillStyle = 'red';
  context.fill();

  context.stroke();

  context.closePath();
}
And yes, I do end up where I belong:


To move myself about, I encapsulate my position inside a player class:
class Player {
  int x, y;
  Player() {
    x = (width/2).toInt();
    y = (height/2).toInt();
  }
  move(String dir) {
    if (dir == 'left') x-= 10;
    if (dir == 'right') x+= 10;
    if (dir == 'up') y-= 10;
    if (dir == 'down') y+= 10;
  }
}
I then define a library global me and direction variable and update draw() to use me instead of coordinates:
Player me;
String direction;

main() {
  CanvasElement canvas = buildCanvas();
  context = canvas.getContext("2d");

  me = new Player();
  draw();
  attachMover();
}
As for the actual movement, I use the attachMover() function to listen for keyboard events—specifically for the arrow keys:
attachMover() {
  // Move on key down
  document.
    on.
    keyDown.
    add((event) {
      direction = null;

      if (event.keyCode == 37) direction = 'left';
      if (event.keyCode == 38) direction = 'up';
      if (event.keyCode == 39) direction = 'right';
      if (event.keyCode == 40) direction = 'down';

      if (direction != null) {
        event.preventDefault();
        me.move(direction);
        draw();
      }
    });

  // Stop on key up
  document.
    on.
    keyUp.
    add((event) {
      direction = null;
    });
}
With that, I can move myself all over my little canvas:


There really was not much different between that experience and doing the same in Javascript. But at least Dart is not getting in my way yet. And there is still lots more to explore...


Day #322

Sunday, May 9, 2010

Baby Steps on Mother's Day

‹prev | My Chain | next›

It is doubtful that I will make much progress this Mother's day. Nevertheless, even on a special day like this, I want to make some progress and keep my chain unbroken. So here goes...

With my code now well-factored and well-behaved, I want to begin the process of seeing others in the <canvas> room as I move about it. Right now, all of the comet communication from the fab.js server is moving an explicitly referenced character around. If I am to move many named characters around, I need a list of all players with which I can interact. But first, players need to be able to identify themselves. For that, I add a form above the <canvas> element:
 <body>
<form id="login" method="get">
<label>Name
<input type="text" name="player">
</label>
<input type="submit" value="Play">
</form>

<canvas id="canvas" width="500" height="500"></canvas>
</body>
I am not doing anything fancy on the server side to prevent duplicate logins (and I do not even have accounts on the server side). For now, I simply want to identify myself via the form. If I have done so, show the room (and tell the server). If not, show the login form. This bit of jQuery does the trick:
$(function() {
var kv = location.search.substr(1).split(/=/);
if (kv[0] == 'player' && kv[1]) {
$('#login').hide();
new Room($("#canvas")[0], {me:kv[1]});
}
else {
$('#canvas').hide();
}
});
I am actually a bit surprised that jQuery does not make query parameter parsing easier than that (no doubt there is a plugin for that). For my purposes however, splitting the query paramter string (location.search) on the key-value separator (=) is enough. If the play parameter is present, then hide the login form and show the room. Otherwise hide the room and leave the form visible to prompt the user to login.

Now that players can identify themselves, I need a mechanism for fab.js to interact with a list of players on all connected browsers. My first attempt initializes with me (so that the server never tries to move me, only I can move me), but provides an interface for the server access players so that it can inform the client that Player objects have moved:
var PlayerList = function(me) {
this.me = me;
this.others = {};
};

PlayerList.prototype.add_player = function(obj) {
if (!this.others[obj.id] && obj.id != this.me.id) {
this.others[obj.id] = new Player(obj.id, obj);
}
};

PlayerList.prototype.get_player = function(id) {
return this.others[id];
};
With this, I can add others to my board (but I handle me as a special case) and I also provide a mechanism to access each player so that I can inform them that they need to move.

I stop there for tonight. Hopefully tomorrow, I will be able to get other players showing up in my room.

Day #98

Friday, May 7, 2010

Stop the Canvas Walker with Comet

‹prev | My Chain | next›

I continue working on my <canvas> / fab.js "game" tonight. After some more refactoring and DRYing up of the code, I am ready to tackle a nagging bug.

The bug is best illustrated in video:



The view-only mode works fine as long as I don't change direction mid-walk. In that case, my character on the view-only screen goes a bit haywire. After a bit of noodling, I think that the cause of this problem is that new walk-to-coordinate does not cancel the previous walk-to-coordinate. Both combine to speed the character off-screen.

The reason this does not happen on the interactive screen is that the event notification method explicitly cancels the previous walk:
Player.prototype.notify = function(evt) {
switch(evt.type) {
case "click":
if (this.walker) clearTimeout(this.walker);
this.walk_to(evt.offsetX, evt.offsetY);
this.notify_server({id:this.id,x:evt.offsetX, y:evt.offsetY});
break;
}
};
If I am correct, then I ought to be able to resolve this by moving the cancel-the-previous-walker code into a separate method that can be called by the comet code driving the view-only walker:
Player.prototype.notify = function(evt) {
switch(evt.type) {
case "click":
this.stop();
this.walk_to(evt.offsetX, evt.offsetY);
this.notify_server({id:this.id,x:evt.offsetX, y:evt.offsetY});
break;
}
};

Player.prototype.stop = function () {
if (this.walker) clearTimeout(this.walker);
};
The javascript code that I push via comet then needs to call this new stop() method:
function broadcast(obj) {
listeners.forEach(
function(listener) {
var body = '<script type="text/javascript">' + "\nconsole.debug('" + obj.body + "')\n</script>\n";
listener({body: body});

body = '<script type="text/javascript">' + "\nloc = " + obj.body + ";\nwindow.parent.me.stop();\nwindow.parent.me.walk_to(loc.x, loc.y);\n</script>\n";
listener({body: body});
}
);
}
With that, I restart my fab.js server and try again:



Ah, much better. Up tomorrow: combining the two <canvas> boards so that I can move around my room and see others as they move around as well.

Day #96

Saturday, May 1, 2010

Connecting Canvas Movements to Fab.js

‹prev | My Chain | next›

Tonight, I continue my exploration of <canvas>, this time with an eye toward hooking it up to fab.js. Last night, I was able to get a small dot representing my character to move about the <canvas> in response to key presses.

That will not work with the "game" my kids have in mind. They'd like a bunch of characters to meander about the board talking to each other. Moving dozens of characters about pixel-by-pixel is something that fab.js/node.js could probably handle, but dealing with network latency and hiccups is probably not worth the effort.

Instead, I will move the character around by having them walk after mouse click. The character will start in the middle of the canvas. A mouse click in the bottom right will result in a animation of my character moving from the middle of the board to the bottom right.

To accomplish this, I publish the clicks from the board to any subscribers interested in being notified. I have no expectation that anything else will be interested in mouse clicks, but pub-sub makes sense here not as a premature generalization, but rather to decouple the game board from my character. So, I establish my <canvas> listeners:
function init() {
var canvas = $("#canvas").get(0);
var ctx = canvas.getContext("2d");

var me = new Player();

canvas_events(canvas, [me]);
draw(ctx, me);
}
My only canvas event:
function canvas_events (canvas, listeners) {
$(canvas).click(function(evt) {
listeners.forEach(
function(listener) { listener.notify(evt) }
);
});
}
(as you may have noticed, I have started using jQuery for my events)

Great, so now I need a Player object that will encapsulate the position of my character and subscribe to the event publications. The instantiation of the class is straight-forward, defaulting to the middle of my 500x500 <canvas>:
var Player = function(options) {
if (!options) options = {};
this.x = options.x || 250;
this.y = options.y || 250;
}
Now, I establish my notify method:
Player.prototype.notify = function(evt) {
switch(evt.type) {
case "click":
this.walk_to(evt.offsetX, evt.offsetY);
break;
}
};
For now, I am only interested in click publications, which initiate a walk:
Player.prototype.walk_to = function(x, y) {
if (this.x < x) this.x = this.x + 1;
if (this.x > x) this.x = this.x - 1;
if (this.y < y) this.y = this.y + 1;
if (this.y > y) this.y = this.y - 1;

if (this.x != x || this.y != y) {
setTimeout(function(){self.walk_to(x,y)}, 25);
}
};
Easy enough!

Now, to tell fab.js what I am up to. I start with my skeleton app:
var puts = require( "sys" ).puts;

with ( require( ".." ) )

( fab )

( listen, 0xFAB )

( 404 );
For now, I am just going to print out the contents of posted location information. I will push that information to other clients later. The fab.js application to do this:
var puts = require( "sys" ).puts;

with ( require( ".." ) )

( fab )

( listen, 0xFAB )

( /move/ )

(
function () {
var out = this;
return function listener( obj ) {
if ( !obj ) out();
else if ( obj.body ) puts(obj.body);
return listener;
};
}
)


( 404 );
To tell my Player class to POST that information, I add a second action in notify():
Player.prototype.notify = function(evt) {
switch(evt.type) {
case "click":
this.walk_to(evt.offsetX, evt.offsetY);
this.notify_server({id:"me",x:evt.offsetX, y:evt.offsetY});
break;
}
};
The server_notify method make a simple jQuery POST:
Player.prototype.notify_server = function(change) {
$.post("http://localhost:4011/move", change);
};
Now, clicking on the board moves my character and tells fab.js:
cstrom@whitefall:~/repos/fab$ node ./play/game.js
id=me&x=322&y=184
id=me&x=364&y=352
id=me&x=199&y=198
id=me&x=350&y=401
Nice! That is a good stopping point for tonight. Tomorrow, I will work on pushing that information to other boards so that others can see my character move.

Day #90

Friday, April 30, 2010

Moving in Canvas

‹prev| My Chain | next›

Tonight, I would like to play about with the <canvas> tag a bit. Ultimately I want to hook it up to fab.js. The <canvas> should represent where my character is and where others are. Tonight, I'll settle for representing where I am on the <canvas>.

First up, I need a <canvas>:
 <body onload="init()">
<canvas id="canvas" width="500" height="500"></canvas>
</body>
I will use a 500x500 grid to keep the math simple—at least to start. Next I need to define that init() function:
function init() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var me = {x:250, y:250};

draw(ctx, me);
}
I grab the <canvas> element and get a 2-D context in it. I have no idea what you can do differently with a 3-D context, nor do I need to know for this experiment. I then define me as being right in the middle of the 500x500 square. With a <canvas> context and me, I am ready to draw:
function draw(ctx, me) {
ctx.beginPath();

// clear drawing area
ctx.clearRect(0,0,500,500);
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = '#000000';
ctx.fillRect(0,0,500,500);

// draw me and fill me in
ctx.rect(me.x,me.y,5,5);

ctx.fillStyle = '#000000';
ctx.fill();

ctx.stroke();

ctx.closePath();
}
The beginPath() call sets the coordinate system back to the top-left of the canvas element. Then I clear the rectangle (good for subsequent calls especially), set the background color to white and the foreground color to black. I fill the <canvas> with the background color then I draw me as a 5x5 box at the specified coordinates.

Loading this in the browser, I get:


Nice off to a good start.

Now I need to animate this, which means call the draw function again at the end of itself:
function draw(ctx, me) {
// draw the canvas and me
setTimeout(function(){draw(ctx, {x:me.x+1,y:me.y})}, 25);
}
Now, when I reload, I move off to the right of the screen:


To actually move, I set handlers on the document to capture keyup and keydown events. When a keydown happens, I start to move (the direction should depend on which arrow key is pressed). When a keyup occurs, I should stop moving:
var direction = null;

document.onkeydown = function(ev) {
switch(ev.keyCode) {
case left:
case up:
case right:
case down:
direction = ev.keyCode;
break;

default:
direction = null;
break;
}

if (direction) return false;
}

document.onkeyup = function(ev) {
direction = null;
}
This is something of a hack, putting the event handler on the entire document and setting a global direction variable. I can live with the hack for now as I am just playing...

The values of up, down, left and right are the key codes that would be sent if they are pressed:
// key codes / directions
var left = 37,
up = 38,
right = 39,
down = 40;
With a global direction representing where I am, I can use that to update my coordinates in draw() accordingly:
function draw(ctx, me) {
// clear the canvas and draw my current position

var x_diff = 0;
if (direction == left) x_diff = -1;
if (direction == right) x_diff = 1;

var y_diff = 0;
if (direction == down) y_diff = 1;
if (direction == up) y_diff = -1;

var me_next = {
x: me.x+x_diff,
y: me.y+y_diff
};

setTimeout(function(){draw(ctx, me_next)}, 25);
}
Just like that, I can move myself about the <canvas>!

Once last thing—I can actually move outside of the canvas as-is. To prevent that, I add a check to the me_next computation:
  var me_next = {
x: (me.x+x_diff > 0 && me.x+x_diff < 500) ? me.x+x_diff : me.x,
y: (me.y+y_diff > 0 && me.y+y_diff < 500) ? me.y+y_diff : me.y
};
You can even try this yourself (complete source code).

That's a good stopping point for tonight. Tomorrow, I will add mouse interaction and send to fab.js for processing.

Day #89