I am building a firefox plugin which allows users to draw any arbitrary figure on an object and save it as an image (png file).
var $ = getJQueryOb();
var canvas = '<canvas id="canvas" width="1024" height="1024" style="position:absolute; top:0px; left:0px;"></canvas>';
var currentWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var mainDoc = currentWindow.getBrowser().contentDocument;
var cObj = $(canvas).appendTo(mainDoc.body);
$(cObj).bind('mousemove', handlePenDraw);
Using this I can draw on the canvas. However, when I save the image, I do not want the full canvas to be saved – rather just the ‘bounding rectangle’ around the image that was created to be saved.
Is there any way I can acheive this. What I am currently doing is going to save the canvas as it is:
var $ = getJQueryOb();
var canvas = $('#canvas')[0];
var dURL = canvas.toDataURL("image/png");
saveToFile(dURL, "image-file.png");
You could store the top left and bottom right coords that have been drawn on in your handlePenDraw method then retrieve the area that has been drawn on using the getImageData method.
Then put the imageData you’ve retrieved onto a new canvas that is only as big as the area drawn on to and then save the new canvas.
Here’s some rough untested code: