Despite the fact that you have to track it yourself, I would suggest wrapping it in reusable functions. Here is a minimal example tracking it only for moveTo and lineTo . See a 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");
source share