admin管理员组

文章数量:1278883

I am attempting to download an entire canvas image using canvas.toDataURL(). The image is a map rendered on the canvas (Open Layers 3).

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('postpose', 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");
}

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.

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:

canvas.toDataURL() for large canvas

Is there a client side work around for this at all?

I am attempting to download an entire canvas image using canvas.toDataURL(). The image is a map rendered on the canvas (Open Layers 3).

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('postpose', 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");
}

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.

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:

canvas.toDataURL() for large canvas

Is there a client side work around for this at all?

Share Improve this question edited May 23, 2017 at 12:02 CommunityBot 11 silver badge asked Feb 18, 2016 at 11:24 Single EntitySingle Entity 3,1233 gold badges42 silver badges66 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

Check out toBlob https://developer.mozilla/en-US/docs/Web/API/HTMLCanvasElement/toBlob

canvas.toBlob(function(blob) {
    exportPNGElement.href = URL.createObjectURL(blob);
});

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.

Just in case you didn't know, you can also dramatically reduce the size using jpeg pression

exportPNGElement.href = canvas.toDataURL('image/jpeg', 0.7);

本文标签: javascriptcanvastoDataURL() download size limitStack Overflow