fur866
fur866

Reputation: 413

Convert SVG Ellipse to Image in Vanilla JavaScript

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.

Upvotes: 0

Views: 169

Answers (1)

Rogier Spieker
Rogier Spieker

Reputation: 4187

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');

Upvotes: 2

Related Questions