Skip to content

Graphics

何波 edited this page Feb 27, 2019 · 30 revisions

Graphics

Graphics类公开了一个易于使用的API,用于生成矢量绘图指令并将它们绘制到指定的上下文。请注意,您可以通过调用graphics/draw来使用图形,而不依赖于easeljs框架。或者直接与Shape对象一起使用,在EaselJS显示列表的上下文上绘制矢量图形。

使用Graphics类有两种方法

  1. 先实例化Graphics类,再调用实例中的方法
  2. new Graphics().command,用Graphics/append将其添加到graphics队列中。

前者抽象后者,简化开始和结束路径、填充和笔画。

var g = new createjs.Graphics();
g.setStrokeStyle(1);
g.beginStroke("#000000");
g.beginFill("red");
g.drawCircle(0,0,30);

所有的绘图方法,都返回Graphics实例,因此方向可以用链式写法。例如,

myGraphics.beginStroke("red").beginFill("blue").drawRect(20, 20, 100, 50);

每个graphics API方法都会生成一个command object

var fillCommand = myGraphics.beginFill("red").command;
// ... later, update the fill style/color:
fillCommand.style = "blue";
// or change it to a bitmap fill:
fillCommand.bitmap(myImage);

为了更直接地控制渲染,可以直接实例化command objects并将其附加到图形队列中。在这种情况下,你需要手动管理路径创建,并确保将fill/stroke应用于定义的路径:

// start a new path. Graphics.beginCmd is a reusable BeginPath instance:
myGraphics.append(createjs.Graphics.beginCmd);
// we need to define the path before applying the fill:
var circle = new createjs.Graphics.Circle(0,0,30);
myGraphics.append(circle);
// fill the path we just defined:
var fill = new createjs.Graphics.Fill("red");
myGraphics.append(fill);

这些方法可以一起使用,例如插入自定义命令:

myGraphics.beginFill("red");
var customCommand = new CustomSpiralCommand(etc);
myGraphics.append(customCommand);
myGraphics.beginFill("blue");
myGraphics.drawCircle(0, 0, 30);

draw()

// 将显示对象绘制到指定的上下文中,忽略其可见、alpha、阴影和转换。
// 如果处理了绘图,则返回true(对于重写功能很有用)。

p.draw = function(ctx, data) {
  this._updateInstructions();
  var instr = this._instructions;
  for (var i=this._storeIndex, l=instr.length; i<l; i++) {
    // 执行command exec命令
    instr[i].exec(ctx, data);
  }
};

append()

@param {Object} command: 一个graphics command object,其有exec方法
@param {boolean} clean: 清除参数主要用于内部使用。如果值为true,则表示`stroked`  `filled`的时候,command不会生成path。
p.append = function(command, clean) {
    // 把command push到当前指令数组中(Uncommitted instructions)
    this._activeInstructions.push(command);
    this.command = command;
    if (!clean) { this._dirty = true; }
    return this;
};

command长什么样子?我们先看一下moveTo方法

p.moveTo = function(x, y) {
  return this.append(new G.MoveTo(x,y), true);
};
// 这里的`new G.MoveTo(x,y)`就是一个command

(G.MoveTo = function(x, y) {
    this.x = x; this.y = y;
}).prototype.exec = function(ctx) { ctx.moveTo(this.x, this.y); };
// command实例必有一个exec方法

command

保留对上一个已创建或附加的命令的引用。例如,可以保留对fill命令的引用,以便以后使用以下命令动态更新颜色:

var myFill = myGraphics.beginFill("red").command;
// update color later:
myFill.style = "yellow";

Clone this wiki locally