Skip to content

Instantly share code, notes, and snippets.

@roboncode
Created October 19, 2016 13:05
Show Gist options
  • Select an option

  • Save roboncode/4bf663b53d2dcf2f05efea22e8a20ea8 to your computer and use it in GitHub Desktop.

Select an option

Save roboncode/4bf663b53d2dcf2f05efea22e8a20ea8 to your computer and use it in GitHub Desktop.
SVG Polygon JavaScript Example
<html>
<head>
<title>Polygon Shape Example</title>
</head>
<body>
<script>
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 this.node.getAttribute(key);
this.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));
};
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.attribute('style', 'fill:lime');
polygon.node; // refer to the actual SVG element
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.appendChild(polygon.node);
document.body.appendChild(svg);
</script>
</body>
</html>
@khackskjs
Copy link

Hello. Thank you for your efforts.
It works well.
I wanna add some method based on this source.
can I use this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment