jonask
jonask

Reputation: 748

Convert SVG element to img

None of related issues has the answer. I want to get my SVG drawing from the DOM, and convert it to being an img.

This is how my function looks now

const SVG = document.querySelector('svg')!;
const canvas = document.createElement('canvas');

const XML = new XMLSerializer().serializeToString(SVG);
const SVG64 = btoa(XML);
const image64 = 'data:image/svg+xml;base64,' + SVG64;

const img = new Image();
img.onload = function() {
  canvas.getContext('2d')!.drawImage(img, 0, 0);
};

img.src = image64;

document.getElementById('container')!.appendChild(img);

And the DOM

<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
   <circle cx="25" cy="25" r="20" />
</svg>

<div id="container"></div>

The result is a blank image. It do has a dataurl as src, but completely blank. Why is that? How should it work?

Upvotes: 0

Views: 3027

Answers (1)

num8er
num8er

Reputation: 19372

Watch errors:

const SVG = document.querySelector('svg')!;
const XML = new XMLSerializer().serializeToString(SVG);
const SVG64 = btoa(XML);

const img = new Image();
img.height = 500;
img.width = 500;
img.src = 'data:image/svg+xml;base64,' + SVG64;

document.getElementById('container')!.appendChild(img);
SVG:<br/>
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
   <circle cx="25" cy="25" r="20" />
</svg>

<hr/>

<div id="container" style="background: red;">
</div>

Seems like You've issue with ! marks: document.querySelector('svg')!, canvas.getContext('2d')!, document.getElementById('container')! - why?

As good practice open inspector panel, console tab of browser to see error messages.

After long talk I understood that Your js code is placed above html elements.

So try to do rendering after window loaded.

Check this:

window.onload = function() {
  renderSVG();
}

const renderSVG = function() {
  const container = document.getElementById('container');
  const svg = document.querySelector('svg');

  if (container && svg) { // since You want to check existence of elements
    const XML = new XMLSerializer().serializeToString(svg);
    const SVG64 = btoa(XML);

    const img = new Image();
    img.height = 500;
    img.width = 500;
    img.src = 'data:image/svg+xml;base64,' + SVG64;

    container.appendChild(img);
  }
};
SVG:<br/>
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
   <circle cx="25" cy="25" r="20" />
</svg>

<hr/>

<div id="container" style="background: red;">
</div>

Upvotes: 3

Related Questions