Another answer describes the correct approach. The main problem is to find boundaries. I get all the image data and in two borders for the search:
function getCanvasBorders(canvas) {
var topleft = {x: false, y: false};
var botright = {x: false, y: false};
for(var x = 0; x < canvas.width; x++) {
for(var y = 0; y < canvas.height; y++) {
if(!emptyPixel(context, x, y)) {
if(topleft.x === false || x < topleft.x) {
topleft.x = x;
}
if(topleft.y === false || y < topleft.y) {
topleft.y = y;
}
if(botright.x === false || x > botright.x) {
botright.x = x;
}
if(botright.y === false || y > botright.y) {
botright.y = y;
}
}
}
}
return {topleft: topleft, botright: botright};
}
SO document, jsfiddle.