我正在构建一个firefox插件,允许用户在对象上绘制任意图形,并将其保存为图像(png文件)。
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);
使用这个我可以在画布上画画。但是,当我保存图像时,我不希望保存整个画布-而只是要保存创建的图像周围的“边界矩形”。
有没有什么办法可以让我。我现在要做的就是按原样保存画布:
var $ = getJQueryOb();
var canvas = $('#canvas')[0];
var dURL = canvas.toDataURL("image/png");
saveToFile(dURL, "image-file.png");
发布于 2010-07-22 16:22:34
您可以存储在handlePenDraw方法中绘制的左上角和右下角坐标,然后使用getImageData方法检索绘制的区域。
然后将检索到的imageData放到一个新的画布上,该画布的大小与绘制到的区域一样大,然后保存新的画布。
div div EDIT:我现在已经创建了一个执行上述操作的演示,只不过它不保存新画布,而只是将其附加到-
下面是一些未经测试的粗略代码:
// Set these with these in your handlePenDraw method.
var topLeftPoint, bottomRightPoint;
var width = bottomRightPoint.x - topLeftPoint.x;
var height = bottomRightPoint.y - topLeftPoint.y;
// Retrieve the area of canvas drawn on.
var imageData = context.getImageData(topLeftPoint.x, topLeftPoint.y, width, height);
// Create a new canvas and put the retrieve image data on it
var newCanvas = document.createElement("canvas");
newCanvas.width = width;
newCanvas.height = height;
newCanvas.getContext("2d").putImageData(imageData, 0, 0);
// Now call save to file with your new canvas
var dURL = newCanvas.toDataURL("image/png");
saveToFile(dURL, "image-file.png");
https://stackoverflow.com/questions/3309571
复制