2011-11-21 11 views
40

Jak utworzyć element SVG z JavaScript? Próbowałem:Utwórz tag SVG z 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); 

Jednak tworzy element SVG o zerowej szerokości i zerowej wysokości.

+0

co przeglądarka robisz to z? –

Odpowiedz

55

Spróbuj tego:

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

Cudownie - dziękuję! Czy to ja, czy SVG jest naprawdę wybredny? – Richard

+1

"svg: svg"? Zwykły stary "svg" też będzie działał dobrze. Również "wersja" jest ignorowana przez wszystkie przeglądarki, więc dodawanie jej jest trochę marnotrawstwem. –

+3

Dzięki @ ErikDahlström, poprawione. A co z svg.setAttributeNS ("http://www.w3.org/2000/xmlns/", "xmlns: xlink", "http://www.w3.org/1999/xlink"); ? Czy przestrzeń nazw jest naprawdę potrzebna? – TeChn4K