仅保存HTML画布的某个部分 [英] Save only a certain part of an HTML canvas
问题描述
是否可以仅保存或导出画布的某个部分而不是整个画布?
Is it possible to save or export only a certain part of the canvas rather than the whole canvas?
http://i.stack.imgur.com/hmvYh.jpg
At那一刻,当我保存文件时,我得到了我在网站上的整个画布元素的构图加上透明背景(上面例子中的浅蓝色)。我想得到的只是灰色区域(可以由几个图像和文本元素组成)。
At the moment, when I save the file I get the composition plus the transparent background (light blue in example above) of the entire canvas element I have on the site. What I would like to get is only the gray region (which could be made up of several images and text elements).
推荐答案
是的你可以。这是 JSFiddle 。
Yes you can. Here is the JSFiddle.
首先,您需要在画布中拍摄图像的剪切
。这很简单。我制作了另一个画布(隐藏的画布)并使用 context.drawImage
First, you need to take a clipping
of the image in your canvas. This is pretty simple. I made another canvas (a hidden one) and used the context.drawImage
var hidden_ctx = hidden_canvas.getContext('2d');
hidden_ctx.drawImage(
MainCanvas,
startClippingX,
startClippingY,
clippingWidth,
clippingHeight,
pasteX,
pasteY,
pasteWidth,
pasteHeight
);
现在,我们需要此画布中的数据URL,以便我们下载内容。为此,我们将使用 canvas.toDataURL
方法。
Now, we need the Data URL from this canvas so we can download the contents. For this, we will use the canvas.toDataURL
method.
var data_url = hidden_canv.toDataURL("image/png");
现在,我们需要做的就是建立下载链接( a
我们的 data_url
的 href
属性的元素,我们已经完成了!
Now, all we need to do is make a download link (an a
element with an href
attribute of our data_url
) and we're done!
这篇关于仅保存HTML画布的某个部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!