getDataURL 获取画布对象的一部分
我正在构建一个 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");
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");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以存储在handlePenDraw 方法中绘制的左上角和右下角坐标,然后使用getImageData 方法检索已绘制的区域。
然后将您检索到的图像数据放到一个新画布上,该画布仅与绘制的区域一样大,然后保存新画布。
这是一些未经测试的粗略代码:
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: