Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

246
Vistas
How to draw a SVG in string format in a canvas html element?

I have a svg in a string, like this:

const svgString = (color) => `<svg height="150" width="500">
  <ellipse cx="240" cy="100" rx="220" ry="30" style="fill:${color}" />
  <ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
  <ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>`;

Please consider that's an example svg, the real one is a little bit larger and more complex, so do not pay a lot of attentiton to that example.

What I want is to draw that SVG string in a canvas. I have tried something like this:

    const canvas = document.createElement('canvas');
    canvas.width = 18;
    canvas.height = 25;
    const ctx = canvas.getContext('2d');
    const path = new Path2D(svgString('red'));
    ctx.drawImage(path, 0, 0, 18, 25);

But that fails with the following error:

"<a class='gotoLine' href='#52:5'>52:5</a> Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'."

Any idea how to solve this?

const svgString = (color) => `<svg height="150" width="500">
  <ellipse cx="240" cy="100" rx="220" ry="30" style="fill:${color}" />
  <ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
  <ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>`;

const canvas = document.createElement('canvas');
canvas.width = 18;
canvas.height = 25;
const ctx = canvas.getContext('2d');
const path = new Path2D(svgString('red'));
ctx.drawImage(path, 0, 0, 18, 25);

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here you have two examples. In both examples I added the SVG namespace to the string, be cause it is a separate XML/SVG document and not haft of the HTML.

In the first example I just create a data URL and insert that as the source of an image object. Here you need to set the width and the height.

In the second example I used Blob and the function URL.createObjectURL().

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

const svgString = (color) => `<svg xmlns="http://www.w3.org/2000/svg" height="150" width="500">
  <ellipse cx="240" cy="100" rx="220" ry="30" style="fill:${color}" />
  <ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
  <ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>`;

var img = new Image();
img.width = 500;
img.height = 150; 

img.addEventListener('load', e => {
  ctx.drawImage(e.target, 0, 0);
});

img.src = `data:image/svg+xml,${svgString('red')}`;
<canvas width="500" height="150" id="canvas"></canvas>

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

const svgString = (color) => `<svg xmlns="http://www.w3.org/2000/svg" height="150" width="500">
  <ellipse cx="240" cy="100" rx="220" ry="30" style="fill:${color}" />
  <ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
  <ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>`;

var svg = new Blob([svgString('red')], {
  type: "image/svg+xml;charset=utf-8"
});

var url = URL.createObjectURL(svg);
var img = new Image();

img.addEventListener('load', e => {
  ctx.drawImage(e.target, 0, 0);
  URL.revokeObjectURL(url);
});

img.src = url;
<canvas width="500" height="150" id="canvas"></canvas>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda