使用SVG多边形元素 [英] Working with SVG polygon elements

查看:118
本文介绍了使用SVG多边形元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SVG多边形和javascript.我创建一个多边形并按如下所示设置其初始点列表:

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('http://www.w3.org/2000/svg','polygon');
polygon.setAttribute("points", "0,0  100,100 200,200");

如果要修改第二点(100,100),该怎么办?现在,我基本上是在重新构建整个字符串.但是我们可以以某种方式将"polygon.points"作为数组来寻址,还是真的只是一个简单的简单字符串?对于非常简单的多边形,这可以正常工作,但是如果我的多边形最终有数百个点对,那么每次我想修改单个元素时,我都不希望将整个点"属性重建为字符串.

now what do I do if I want to modify the 2nd point (100,100)? Right now I'm basically reconstructing the whole string again. But can we address "polygon.points" as an array somehow, or is it really just a plain simple string? This can work ok for very simple polygons, but if my polygon eventually has hundreds of point pairs, I'd hate to reconstruct the entire "points" attribute as a string every time I want to modify a single element.

谢谢

推荐答案

恐怕无法解决.您必须再次重建字符串.但是将整个内容包装在一个对象中并不困难,例如:

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.

这篇关于使用SVG多边形元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆