Creating SVG elements dynamically with javascript inside HTML

前端 未结 3 1524
轮回少年
轮回少年 2020-11-28 20:33

I want to create a rectangle inside an HTML page, then write some text on that rectangle. I also need that text to be a hyperlink. This is what I did but it is not working:<

3条回答
  •  天命终不由人
    2020-11-28 20:45

    To facilitate svg editing you can use an intermediate function:

    function getNode(n, v) {
      n = document.createElementNS("http://www.w3.org/2000/svg", n);
      for (var p in v)
        n.setAttributeNS(null, p, v[p]);
      return n
    }
    

    Now you can write:

    svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );
    

    Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

    function getNode(n, v) {
      n = document.createElementNS("http://www.w3.org/2000/svg", n);
      for (var p in v)
        n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);
      return n
    }
    
    var svg = getNode("svg");
    document.body.appendChild(svg);
    
    var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });
    svg.appendChild(r);
    
    var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });
    svg.appendChild(r);

提交回复
热议问题