Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

javascript - canvas.toDataURL() download size limit

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out toBlob https://developer.mozilla.org/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 compression

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...