Created
October 19, 2016 13:05
-
-
Save roboncode/4bf663b53d2dcf2f05efea22e8a20ea8 to your computer and use it in GitHub Desktop.
SVG Polygon JavaScript Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello. Thank you for your efforts.
It works well.
I wanna add some method based on this source.
can I use this?