I was surprised this functionality was missing, so I went ahead and wrote it.
(createjs.Graphics.Polygon = function(x, y, points) {
this.x = x;
this.y = y;
this.points = points;
}).prototype.exec = function(ctx) {
var start = this.points[0];
ctx.moveTo(start.x, start.y);
this.points.slice(1).forEach(function(point) {
ctx.lineTo(point.x, point.y);
});
ctx.lineTo(start.x, start.y);
}
createjs.Graphics.prototype.drawPolygon = function(x, y, args) {
var points = [];
if (Array.isArray(args)) {
args.forEach(function(point) {
point = Array.isArray(point) ? {x:point[0], y:point[1]} : point;
points.push(point);
});
} else {
args = Array.prototype.slice.call(arguments).slice(2);
var x = null;
args.forEach(function(val) {
if (x == null) {
x = val;
} else {
points.push({x: x, y: val});
x = null;
}
});
}
return this.append(new createjs.Graphics.Polygon(x, y, points));
}
This will add a drawPolygon()
method to the graphics object that can be called in 3 ways.
Points as separate arguments drawPolygon(x, y, p1x, p1y, p2x, p2y, ...)
Points as an array of arrays drawPolygon(x, y, [[p1x, p1y], [p2x, p2y], ...])
Points as an array of objects drawPolygon(x, y, [{x:p1x,y:p1y}, {x:p2x,y:p2y}, ...])
Eg:
poly1.graphics.beginFill("Red").drawPolygon(0,0,10,10,10,40,40,30,60,5,30,0);
poly2.graphics.beginFill("Green").drawPolygon(0,0,[[10, 10], [10, 40], [40, 30], [60, 5], [30,0]]);
poly3.graphics.beginFill("Blue").drawPolygon(0,0,[{x:10,y:10}, {x:10,y:40}, {x:40,y:30}, {x:60,y:0}]);
See a working fiddle at https://jsfiddle.net/k3rgk11e/2/