Question

I'm working on a canvas app, and I need to be able to create bitmaps, lines, groups,and manage click events.

I tried:

  1. kinetic-v3.9.6.js
  2. easeljs-0.4.2.min.js

These are very nice tools but they don't have a way to get the width of a group of bitmaps and lines. Picture this:

//init a image
var b = new Bitmap(...);
b.x ...
b.src ...

var l = Line(...);
l.x ...
l.y ...

//init group or layer or something like that
var g = Group(...);
g.add(b);
g.add(l);

var w = g.width;

This doesn't work.

Right now I'm considering hacking the easeljs-0.4.2.min.js to accomplish this because it is a good starting point to port as3/as2 simple code, but I'm not sure if this is a good idea.

I really like the way Flash implements display objects, so if you know of some tool please let me know.

Was it helpful?

Solution

You could/should use SVG for what you are describing.

Demo: http://jsfiddle.net/mNAd3/

var svgNS = 'http://www.w3.org/2000/svg',
    svg   = document.body.appendChild(document.createElementNS(svgNS,'svg'));

var l = document.createElementNS(svgNS,'line');
line.setAttribute('x1',10); line.setAttribute('y1',50);
line.setAttribute('x2',30); line.setAttribute('y2',150);

var g = svg.appendChild(document.createElementNS(svgNS,'g'));
g.appendChild(l);

var bbox = g.getBBox();
console.log(bbox);
// SVGRect:
//   height: 100
//   width: 20
//   x: 10
//   y: 50

var w = bbox.width;

Note that you will need to ensure that your elements are visible on screen (adding the SVG to the document, adding the group to the SVG) to calculate the bounding box.

I intentionally did not include an example of creating an image because with asynchronously-loaded resources you need to set an load handler to wait for the image to load, and I didn't want to complicate the demo with those details.

Because SVG is a retained-mode graphics API it has concepts for the sizes of objects and allows them to track and handle mouse events. This is not true for HTML5 canvas (because it is an immediate-mode graphics API.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top