hammerlab/data-canvas

Name: data-canvas

Owner: Hammer Lab

Description: Improved event handling and testing for the HTML5 canvas

Created: 2015-09-28 20:08:57.0

Updated: 2017-09-24 04:51:14.0

Pushed: 2015-11-04 23:11:43.0

Homepage: null

Size: 322

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

Build Status Coverage StatusGitter

data-canvas

data-canvas allows you to add event tracking and tests to existing canvas code without sacrificing performance and without forcing you to refactor.

It does this by introducing a new abstraction to canvas: the data stack.

Background

The HTML5 canvas has several advantages over SVG, its main rival for graphics on the web:

That being said, canvas also has some major drawbacks:

data-canvas aims to overcome some of these drawbacks without compromising canvas's speed and simplicity.

A canvas example

Here's a bit of data representing a car:

car = {
me: 'Box car',
 100,
 100,
dth: 200,
eels: [
{name: 'back wheel', x: 20, radius: 15},
{name: 'front wheel', x: 180, radius: 10}


You might render it using canvas like so:

tion renderScene(ctx, car) {
x.fillStyle = 'red';
x.fillRect(car.x, car.y, car.width, -25);
x.fillRect(car.x + 50, car.y - 25, car.width - 100, -25);
x.fillStyle = 'black';
x.strokeStyle = 'gray';
r.wheels.forEach(function(wheel) {
ctx.beginPath();
ctx.arc(car.x + wheel.x, car.y, wheel.radius, 0, Math.PI*2, true);
ctx.fill();
ctx.stroke();
;


tion renderBoxyCar() {
r ctx = canvas.getContext('2d');
nderScene(ctx, car);

Boxy red car with two black wheels

(see full demo)

This is a beautiful car and a faithful rendering of the data. But what if you wanted to add a click handler to it? What if you wanted to write a test which asserted that there were two wheels?

data-canvas can help you do both of these.

The data stack

“All problems in computer science can be solved by another level of indirection.“

data-canvas wraps the browser's canvas rendering context with a DataContext, which adds two new primitives:

are class DataCanvasRenderingContext2D extends CanvasRenderingContext2D {
shObject(o: any): void;
pObject(): void;

These primitives associate a data stack with the canvas rendering context. Whenever you render a bit of data, you should push it onto the data stack. When you're done with it, you pop it off.

Here's what the car example looks like using a DataContext:

tion renderScene(ctx) {
x.pushObject(car);  // <---
x.fillStyle = 'red';
x.fillRect(car.x, car.y, car.width, -25);
x.fillRect(car.x + 50, car.y - 25, car.width - 100, -25);
x.fillStyle = 'black';
x.strokeStyle = 'gray';
r.wheels.forEach(function(wheel) {
ctx.pushObject(wheel);  // <---
ctx.beginPath();
ctx.arc(car.x + wheel.x, car.y, wheel.radius, 0, Math.PI*2, true);
ctx.fill();
ctx.stroke();
ctx.popObject();  // <---
;
x.popObject();  // <---


tion renderBoxyCar() {
r ctx = dataCanvas.getDataContext(canvas.getContext('2d'));   // <---
nderScene(ctx);

The new code is marked by comments. The pushObject/popObject calls fit nicely into the existing code without changing its style.

Here's what the data stack looks like while the rendering happens:

Testing

Using this modified code, we can write a test:

ribe('boxy car', function() {
('should have two wheels', function() {
var RecordingContext = dataCanvas.RecordingContext;
RecordingContext.recordAll();  // stub in a recording data context
renderBoxyCar();

var wheels = RecordingContext.drawnObjectsWith(x => x.radius);
expect(wheels).to.have.length(2);
expect(wheels[0].name).to.equal('back wheel');
expect(wheels[1].name).to.equal('front wheel');

RecordingContext.reset();  // restore the usual data context
;

The RecordingContext.recordAll() call swaps in an alternate implementation of DataContext which records every method called on it. This includes the pushObject calls. After the drawing is done, we can access the drawn objects using its helper methods, such as drawnObjectsWith.

It's typically easiest to make assertions about the objects pushed onto the data stack, but you can make assertions about the underlying drawing commands, too:

ribe('boxy car', function() {
('should draw two wheels', function() {
var RecordingContext = dataCanvas.RecordingContext;
RecordingContext.recordAll();  // stub in a recording data context
renderBoxyCar();
RecordingContext.reset();  // restore the usual data context

var wheels = RecordingContext.callsOf('arc');
expect(wheels).to.have.length(2);
expect(wheels[0].slice(0, 3)).to.deep.equal(['arc', 120, 100, 15]);
expect(wheels[1].slice(0, 3)).to.deep.equal(['arc', 280, 100, 10]);
;

Writing the test required no modifications to the rendering code beyond the pushObject/popObject calls.

Click tracking

data-canvas also facilitates mapping (x, y) coordinates to objects in the scene.

Suppose you wanted to add click handlers to the wheels and the car itself. Here's how you might do that:

as.onclick = function(e) {
r ctx = canvas.getContext('2d');
r trackingContext = new dataCanvas.ClickTrackingContext(ctx, e.offsetX, e.offsetY);
nderScene(trackingContext);

 (trackingContext.hit) {
alert(trackingContext.hit[0].name);


(Try it with this fiddle)

Again, no modifications to the scene rendering code were required. To determine which object (if any) was clicked on, we swapped in an alternate data context (ClickTrackingContext) and redrew the scene.

While redrawing the scene may feel inefficient, it rarely is. ClickTrackingContext doesn't need to draw any shapes, only check whether they contain the relevant point.

After rendering the scene, ClickTrackingContext will have both a hit and a hits property. hit records the contents of the data stack for the last (top-most) shape which contains the point. hits records the contents for all shapes which contained the point, ordered from top to bottom.

For example, if you click the top part of the back wheel, then we'll have:

hit = [back wheel, car]

Because both the car and the back wheel were on the data stack when the car was drawn.

We'll also have:

hits = [[back wheel, car], [car]]

This is because only car was on the stack when the car rectangle was drawn, and another shape (the wheel) was drawn on top of it.

Usage

To install data-canvas, use NPM:

npm install data-canvas

Then include it either in your page:

<script src="node_modules/data-canvas/data-canvas.js"></script>

or require it:

var dataCanvas = require('data-canvas');

data-canvas comes with type bindings for Flow. To use these, add the following to your .flowconfig:

ore]
de_modules/data-canvas.*

]
_modules/data-canvas/flowtype

This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.