如何使用EaselJS绘制多边形?

qui*_*ilv 9 javascript html5 canvas easeljs createjs

有Shape.graphic方法可以轻松绘制圆形和矩形,但没有明显的方法可以绘制多边形,如六边形和多边形?你如何使用EaselJS绘制它们?

qui*_*ilv 11

实际上它非常简单,只需要使用方法moveTo和lineTo.绘制简单三角形的示例,

var polygon = new createjs.Shape();
polygon.graphics.beginStroke("black");
polygon.graphics.moveTo(0, 60).lineTo(60, 60).lineTo(30, 90).lineTo(0, 60);
Run Code Online (Sandbox Code Playgroud)

并且想到它,不需要一种drawPolygon方法.在我看来,它不会被广泛使用.

  • 我们可以用颜色填充这个createjs.Shape吗? (3认同)

Lan*_*nny 7

有一种drawPolyStar方法,可用于绘制几何形状. http://www.createjs.com/Docs/EaselJS/classes/Graphics.html#method_drawPolyStar

任何不规则的东西都可以使用之前@quik_silv提到的Shape lineTo和moveTo方法(记得在绘图之前开始描边或填充).

第三方工具可以导出更复杂的形状,例如Flash CC(使用Toolkit for CreateJS或新的Canvas文档).Illustrator的DrawScript插件可以非常轻松地将Illustrator路径导出到CreateJS,包括紧凑格式.http://drawscri.pt/

干杯.


Tyr*_*ris 6

我很惊讶这个功能丢失了,所以我继续写下来.

(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));
}
Run Code Online (Sandbox Code Playgroud)

这将为drawPolygon()图形对象添加一个方法,可以通过3种方式调用.

指向单独的参数 drawPolygon(x, y, p1x, p1y, p2x, p2y, ...)

指向一个数组数组 drawPolygon(x, y, [[p1x, p1y], [p2x, p2y], ...])

指向一个对象数组 drawPolygon(x, y, [{x:p1x,y:p1y}, {x:p2x,y:p2y}, ...])

例如:

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}]);
Run Code Online (Sandbox Code Playgroud)

在https://jsfiddle.net/k3rgk11e/2/上看到一个工作小提琴