Working with SVG polygon elements

前端 未结 4 549
暖寄归人
暖寄归人 2021-02-05 09:39

I\'m trying to work with an SVG polygon and javascript. I create a polygon and set its initial point list like this:

var polygon = document.createElementNS(\'htt         


        
相关标签:
4条回答
  • 2021-02-05 09:47

    No way around it I'm afraid. You have to reconstruct the string again. But it's not difficult to wrap the whole thing in an object, something like:

    function Polygon () {
        var pointList = [];
        this.node = document.createElementNS('http://www.w3.org/2000/svg','polygon');
        function build (arg) {
            var res = [];
            for (var i=0,l=arg.length;i<l;i++) {
                res.push(arg[i].join(','));
            }
            return res.join(' ');
        }
        this.attribute = function (key,val) {
            if (val === undefined) return node.getAttribute(key);
            node.setAttribute(key,val);
        }
        this.getPoint = function (i) {return pointList[i]}
        this.setPoint = function (i,x,y) {
            pointList[i] = [x,y];
            this.attribute('points',build(pointList));
        }
        this.points = function () {
          for (var i=0,l=arguments.length;i<l;i+=2) {
              pointList.push([arguments[i],arguments[i+1]]);
          }
          this.attribute('points',build(pointList));
        }
        // initialize 'points':
        this.points.apply(this,arguments);
    }
    
    var polygon = new Polygon(0,0, 100,100, 200,200);
    polygon.setPoint(0, 50,10); // set point and automatically re-build points
    polygon.points(50,50, 50,100, 200,100); // set everything
    polygon.node; // refer to the actual SVG element
    

    * not the best implementation but you get the idea.

    0 讨论(0)
  • 2021-02-05 09:50

    You need to use setAttributeNS. You'll probably want to cache that namespace in a variable somewhere so you don't have to keep typing it.

    0 讨论(0)
  • 2021-02-05 09:50

    You need to set all points at once, the performance is pretty solid, what you may want to do is manage the array outside and merge it on the setAttribute calls

    0 讨论(0)
  • 2021-02-05 09:59

    You can access the individual point values using the SVG DOM:

    var p = polygon.points.getItem(1);
    p.x = 150;
    p.y = 300;
    

    (Assuming that your UA implements this interface.) See SVGPolygonElement, SVGAnimatedPoints, SVGPointList and SVGPoint.

    I find though that using these SVG DOM interfaces (at least for me in Batik, in which I do most of my SVG stuff) is often not faster than just updating the attribute with string manipulation.

    0 讨论(0)
提交回复
热议问题