[whatwg] Should Paths be First Class Citizens?

David Geary david.mark.geary at gmail.com
Wed Aug 31 10:48:36 PDT 2011


I’ve implemented some polygon objects for my book that I can drag around in
a canvas. I detect mouse clicks in the polygons with the isPointInPath()
method. Here’s a simple code snippet that detects mouse clicks in a set of
polygons (dnd code is too lengthy for this purpose):

context.canvas.onmousedown = function (e) {
   var loc = windowToCanvas(context.canvas, e);

   polygons.forEach( function (polygon) {  // polygons is an array of
polygon objects
      polygon.createPath();  // my polygons have a createPath() method

      if (context.isPointInPath(loc.x, loc.y)) {
         alert('mouse clicked in polygon');
      }
   });
}

Notice that I have to recreate each path for every polygon.
Polygon.createPath() is implemented with beginPath()...moveTo()...repeated
calls to lineTo()...and finally...closePath().

It seems to me that it would be great if the Canvas context provided two new
methods: Path getPath(), which would return a path object representing the
context’s current path, and setPath(Path), which would set the current path.

Those two methods seem like they’d be easy for UAs to implement. It also
seems like they would, under certain circumstances, give a significant boost
to performance. If I have thousands of polygons, for example, I must be
paying some price for all that path building.


David
Author of Core HTML5 Canvas (corehtml5canvas.com)


More information about the whatwg mailing list