0

svg 画像とテキスト オブジェクトを作成しようとしていますが、これらのオブジェクトは両方とも、xlink:href および xml:space プロパティを設定するために名前空間が必要です。これらのオブジェクトを作成する運がなかったので、画面に追加できるように、次のコードを試しました。

function createSVGNode(node) {
    var svg = document.createElementNS('http://www.w3.org/1999/xlink', 'svg');
    var ns2 = null;
    if(node.nodeName == 'image') { ns2 = 'http://www.w3.org/1999/xlink'; }
    var shape = document.createElementNS(ns2, node.nodeName);
    svg.appendChild(shape);
    var ns = null;
    for(var attr = 0; attr < node.attributes.length; attr++) {
        if(node.nodeName == 'image' && node.attributes[attr].nodeName == 'xlink:href') {
            ns = 'http://www.w3.org/1999/xlink';
        }
        if(node.nodeName == 'text' && node.attributes[attr].nodeName == 'xml:space') {
            ns = 'http://www.w3.org/XML/1998/namespace';
        }
        shape.setAttributeNS(ns, node.attributes[attr].nodeName, node.attributes[attr].nodeValue);
        ns = null;
    }
    if(node.childNodes.length == 1) shape.appendChild(node.childNodes[0]);
    return shape;
}

これについては必要以上に難しいと思いますが、画像とテキスト オブジェクトを処理しなければならないまで、すべてが機能していました。

4

1 に答える 1

0

SVG 要素は SVG 名前空間にあります

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var shape = document.createElementNS('http://www.w3.org/2000/svg', node.nodeName);
svg.appendChild(shape);
var ns = null;
for(var attr = 0; attr < node.attributes.length; attr++) {
    if(node.nodeName == 'image' && node.attributes[attr].nodeName == 'xlink:href') {
        ns = 'http://www.w3.org/1999/xlink';
    }
    if(node.nodeName == 'text' && node.attributes[attr].nodeName == 'xml:space') {
        ns = 'http://www.w3.org/XML/1998/namespace';
    }
    shape.setAttributeNS(ns, node.attributes[attr].nodeName, node.attributes[attr].nodeValue);
    ns = null;
}
if(node.childNodes.length == 1) shape.appendChild(node.childNodes[0]);
return shape;
于 2013-10-10T14:29:41.997 に答える