Canvas 'tainted' after drawing SVG

1.3k Views Asked by At

Similar questions have been asked, and the REASON for the problem is well understood, what I'm asking for is alternatives or work-arounds:

What I'd like to do is get a data-URL out of a canvas that has an SVG document drawn onto it. I've tried all kinds of things, but IE9 and Chrome just won't let me have that URL as soon as SVG comes anywhere near that canvas.

I've tried:

  • Canvg (doesn't support everything I need)
  • Drawing the svg file directly to the canvas (content.drawImage(svg, 0 0))
  • Creating a base64 string of the whole svg document, making it the source of an and then drawing that image onto the canvas.
  • Saving the svg to a file, set an src attribute to point at the file (on the same domain), then draw that to the canvas

I'm running out of ideas.

Are there similar libraries I can try that will rasterize svg? Is there maybe something else I can convert SVG to before drawing so that the canvas never knows SVG was involved? Is there maybe a really simple way to do the conversion server-side with PHP or something similar?

2

There are 2 best solutions below

0
On

do three things,

  1. get the SVG and parse it using XMLSerializer
  2. change the canvas height and width before drawing the SVG
  3. use "canvg" library to parse the SVG instead of using the canvas on browser with native canvas methods.
//Get SVG element and then serialize it to convert to a stream of String
var svg = document.querySelectorAll('svg');
var base64 = [];
for(i=0; i < svg.length; i++){
var serializer = new XMLSerializer();
var svgString = serializer.serializeToString(svg[i]);
var canvas = document.querySelectorAll('canvas');
var render_width = 1000;
var render_height = 600;

//CHange/Set Canvas width/height attributes to reset origin-clean flag
canvas[i].height = render_height;
canvas[i].width = render_width;

//Use canvg library to parse SVG and draw the image on given canvas
canvg(canvas[i], svgString, {
useCORS: true,
scaleWidth: render_width,
scaleHeight: render_height,
ignoreDimensions: true,
log: true
});

//Convert canvas to png formated dataURL and save the body of it
var rawImage = canvas[i].toDataURL("image/png");

//Array containing all the images in the form of base64 data URLs.
base64ImageArray.push(rawImage);
}

Hope this helps.

0
On

If you want to rasterize SVG, here are a few projects:

Here's a browser compatibility table: