2011-11-21 21 views
40

¿Cómo creo un elemento SVG con JavaScript? He intentado esto:Crear etiqueta SVG con JavaScript

var svg = document.createElement('SVG'); 
    svg.setAttribute('style', 'border: 1px solid black'); 
    svg.setAttribute('width', '600'); 
    svg.setAttribute('height', '250'); 
    svg.setAttribute('version', '1.1'); 
    svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); 
document.body.appendChild(svg); 

Sin embargo, crea un elemento SVG con un ancho de cero y altura cero.

+0

qué navegador estás haciendo esto con? –

Respuesta

55

Prueba esto:

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 
svg.setAttribute('style', 'border: 1px solid black'); 
svg.setAttribute('width', '600'); 
svg.setAttribute('height', '250'); 
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); 
document.body.appendChild(svg); 
+6

Maravilloso, ¡gracias! ¿Soy yo o SVG realmente meticuloso? – Richard

+1

"svg: svg"? El simple "svg" también funciona bien. Además, todos los navegadores ignoran la "versión", por lo que es un desperdicio agregar eso. –

+3

Gracias @ ErikDahlström, corregido. ¿Y qué pasa con svg.setAttributeNS ("http://www.w3.org/2000/xmlns/", "xmlns: xlink", "http://www.w3.org/1999/xlink"); ? ¿El espacio de nombres es realmente necesario? – TeChn4K

Cuestiones relacionadas