Although you have to track it yourself, I would suggest wrapping it up in reusable functionality. Here's a minimal example, tracking it only for moveTo
and lineTo
. See the live example here: http://phrogz.net/tmp/canvas_bounding_box.html
function trackBBox( ctx ){
var begin = ctx.beginPath;
ctx.beginPath = function(){
this.minX = this.minY = 99999999999;
this.maxX = this.maxY = -99999999999;
return begin.call(this);
};
ctx.updateMinMax = function(x,y){
if (x<this.minX) this.minX = x;
if (x>this.maxX) this.maxX = x;
if (y<this.minY) this.minY = y;
if (y>this.maxY) this.maxY = y;
};
var m2 = ctx.moveTo;
ctx.moveTo = function(x,y){
this.updateMinMax(x,y);
return m2.call(this,x,y);
};
var l2 = ctx.lineTo
ctx.lineTo = function(x,y){
this.updateMinMax(x,y);
return l2.call(this,x,y);
};
ctx.getBBox = function(){
return {
minX:this.minX,
maxX:this.maxX,
minY:this.minY,
maxY:this.maxY,
width:this.maxX-this.minX,
height:this.maxY-this.minY
};
};
}
...
var ctx = myCanvas.getContext("2d");
// Cause the canvas to track its own bounding box for each path
trackBBox(ctx);
ctx.beginPath();
ctx.moveTo(40,40);
for(var i=0; i<10; i++) ctx.lineTo(Math.random()*600,Math.random()*400);
// Find the bounding box of the current path
var bbox = ctx.getBBox();
ctx.strokeRect(bbox.minX,bbox.minY,bbox.width,bbox.height);