0

Hey guys I have got the following SVG with Ellipse in it:

     <svg xmlns="http://www.w3.org/2000/svg" version="1.1" 
xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16">
          <ellipse cx="50%" cy="50%" rx="50%" ry="50%" fill="#fefefe"></ellipse>
        </svg>

I want to convert the above one (which is in string format btw) into an Image so that I can then use it on canvas using putImageData. Any help would be much appreciated.

Michael Mullany
  • 30,283
  • 6
  • 81
  • 105
fur866
  • 413
  • 1
  • 5
  • 14
  • This might help http://stackoverflow.com/questions/3975499/convert-svg-to-image-jpeg-png-etc-in-the-browser – Vinod Louis Dec 09 '16 at 11:23
  • @VinodLouis Thanks but those answers require some use of libraries. I have to do it in just Vanilla JS. – fur866 Dec 09 '16 at 11:26

1 Answers1

2

As a <canvas> element does not allow for <svg> to be drawn onto it directly, you'll have to "convert" it to an <img> first.

This is a rather simple process involving a (short) number of steps:

Place the SVG into an image. This can be done by creating an <img> and setting its .src to a data-url containing the SVG.

var svg = document.querySelector('svg'),
    img = document.createElement('img');

img.src = 'data:image/svg+xml;utf8,' + svg.outerHTML;

This may be a little more complicated if the SVG will contain characters you need to escape (especially a # can be nasty).

Place the image onto the canvas. A canvas has a context which allows for <img> (and others, but not <svg>) to be drawn into it.

var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');

//  now that we have the SVG nicely embedded in an image, we can
//  use the image to size the canvas
canvas.width = img.width;
canvas.height = img.height;

//  and draw the image onto the canvas (in the top/left corder) 
//  using the context 
ctx.drawImage(img, 0, 0);

a working fiddle for you to play with


As the question itself is tagged with svg-filters and these will require the #, you may want to rewrite the assignment of img.src to something like:

img.src = svg.outerHTML.replace(/#/g, '%23');
Rogier Spieker
  • 4,087
  • 2
  • 22
  • 25