问题描述
我正在尝试使用 canvas.toDataURL() 下载整个画布图像.图像是在画布上渲染的地图(打开第 3 层).
I am attempting to download an entire canvas image using canvas.toDataURL(). The image is a map rendered on the canvas (Open Layers 3).
在 Firefox 中,我可以使用以下链接来下载地图:
In Firefox I can use the following to download the map on the click of a link:
var exportPNGElement = document.getElementById('export_image_button');
if ('download' in exportPNGElement) {
map.once('postcompose', function(event) {
var canvas = event.context.canvas;
exportPNGElement.href = canvas.toDataURL('image/png');
});
map.renderSync();
} else {
alert("Sorry, something went wrong during our attempt to create the image");
}
但是在 Chrome 和 Opera 中,我遇到了链接的大小限制.我必须物理缩小窗口才能下载工作.
However in Chrome and Opera I'm hitting a size limit on the link. I have to physically make the window smaller for the download to work.
浏览器之间存在大小限制差异,Chrome 尤其受到限制.此处的类似帖子(现在已超过 2 年)提出了广泛的服务器端解决方法:
There are size limit differences between browsers, Chrome is particularly limiting. A similar post here (over 2 years old now) suggests an extensive server side workaround:
是否有客户端解决此问题?
Is there a client side work around for this at all?
推荐答案
查看 toBlob
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
canvas.toBlob(function(blob) {
exportPNGElement.href = URL.createObjectURL(blob);
});
浏览器支持并不像 toDataURL
那样出色.但是 Chrome 和 Firefox 有它,所以它解决了你最大的问题.上面的 mdn 链接也有一个基于 toDataURL
的 polyfill,所以你会得到最好的支持.
browser support is not as awesome as toDataURL
though. But Chrome and Firefox have it, so it solves your biggest issue. The mdn link above also has a polyfill based on toDataURL
, so you get the best possible support.
以防万一您不知道,您还可以使用 jpeg 压缩显着减小大小
Just in case you didn't know, you can also dramatically reduce the size using jpeg compression
exportPNGElement.href = canvas.toDataURL('image/jpeg', 0.7);
这篇关于canvas.toDataURL() 下载大小限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!