this is a big issue for me at the moment...
I'm rendering a world map via Path shapes... problem is the Path Shape does not offer width or height,
so caching or other simple operations become really hard to do.
e.g. what x/y height/width to I give to path.toImage
?
Any idea how I could get around this problem?
If the world map path is made up of a series of lines (as it often is), you can get the bounding box of the path by looking for the minX/minY and maxX/maxY coordinates in your path data.
I just had to solve this same problem with Kinetic JS.
This code below looks through some random canvas draw code which contains (x,y) coordinates, extracts the coordinates into an array, looks through for the min and max of both X and Y, and shows the width and height of the shape.
From this you should have a bounding box.
var regex = /[+-]?\d+\.\d+/g;
var str = 'ctx.bezierCurveTo(30.1, 220.7, 82.8, 233.0, 147.8, 233.0); ctx.bezierCurveTo(213.1, 233.0, 266.6, 220.8, 266.6, 205.7); ctx.bezierCurveTo(266.6, 205.3, 267.0, 205.1, 267.0, 204.7);';
var floats = str.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats);
var minX = 99999;
var maxX = -99999;
var minY = 99999;
var maxY = -99999;
for ( var i = 0; i < floats.length; i++ ) {
if ( isOdd(i) ) { // the array of numbers is in the form (x,y,x,y,x,y,x...)
// Check Y values
if ( floats[i] < minY ) { minY = floats[i]; }
if ( floats[i] > maxY ) { maxY = floats[i]; }
} else {
// Check X values
if ( floats[i] < minX ) { minX = floats[i]; }
if ( floats[i] > maxX ) { maxX = floats[i]; }
}
}
console.log('minX = ' + minX + ', minY = ' + minY + ', maxX = ' + maxX + ', maxY = ' + maxY);
function isOdd(num) { return num % 2;}