Reputation: 76
I'am using D3 to generate a graph and want to export this to an image, which works fine in all browsers except Safari. The code generates a D3 SVG, which is used in a BLOB, which is used as an image, which is added to a canvas which can be exported.
var blob = new Blob([source], { type: 'image/svg+xml;charset=utf-8' });
var url = window.URL.createObjectURL(blob);
// Put the svg into an image tag so that the Canvas element can read it in.
var img = d3.select('body').append('img')
.attr('width', width)
.attr('height', height)
.node();
img.onload = function(){
// Some method which is never called
}
img.src = url;
In Safari, the onload function is never triggered and the image element is also not displaying the image. I logged both the blob element and URL and both seem fine (if i manually open the blob URL in safari it downloads the SVG code). But it won't display it as an image and therefore i can't export it.
Something i noticed is that when i inspect the img element and open the src in a new tab it opens on the URL https://www.mysite.nl/mypage/blob:https://www.mysite.nl/2a173f60-8b34-4b1c-894b-4ff6adcfe9fa
So for some reason Safari interprets the BLOB URL as a relative instead of an absolute one. Anyone got an idea on how to fix this?
Upvotes: 4
Views: 16382
Reputation: 136598
Safari doesn't like your Blob's MIME Type.
The correct one is image/svg+xml
the charset header is useless, and while I'm not sure it's actually allowed to be there, it is anyway useless.
So remove the ;charset=utf-8
part from your type
option, and you'll be fine:
var blob = new Blob(['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect y="0" width="100" height="100" rx="15" ry="15" x="0"></rect></svg>'], {
type: 'image/svg+xml' // this is the only MIME for SVG
});
document.body.appendChild(
new Image()
).src = URL.createObjectURL(blob);
Upvotes: 18