pixijs-scene-graphics

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Graphics
is the vector-drawing leaf of the PixiJS v8 scene graph. The v8 API follows a shape-then-style pattern: draw a shape or path with
rect
,
circle
,
moveTo
, etc., then apply
fill
and/or
stroke
. Every method returns
this
for chaining, and the drawing instructions live on a
GraphicsContext
that can be shared between instances.
Assumes familiarity with
pixijs-scene-core-concepts
.
Graphics
is a leaf: do not nest children inside it. Wrap multiple
Graphics
objects in a
Container
to group them.
Graphics
是PixiJS v8场景图中的矢量绘制叶子节点。v8 API遵循「先绘形状再设样式」的模式:使用
rect
circle
moveTo
等方法绘制形状或路径,然后应用
fill
和/或
stroke
。所有方法都返回
this
以支持链式调用,绘制指令存储在
GraphicsContext
中,该上下文可在多个实例之间共享。
本文假设你已熟悉
pixijs-scene-core-concepts
Graphics
是叶子节点:请勿在其中嵌套子元素。如需分组多个
Graphics
对象,请将它们包装在
Container
中。

Quick Start

快速开始

ts
const g = new Graphics();

g.rect(10, 10, 200, 100)
  .fill({ color: 0x3498db, alpha: 0.8 })
  .stroke({ width: 3, color: 0x2c3e50 });

g.circle(300, 60, 40).fill(0xe74c3c);

g.moveTo(50, 200)
  .lineTo(200, 200)
  .bezierCurveTo(250, 250, 100, 300, 50, 250)
  .closePath()
  .fill(0x6c5ce7);

app.stage.addChild(g);
Related skills:
pixijs-scene-core-concepts
(scene graph basics),
pixijs-scene-container
(group graphics with other objects),
pixijs-scene-core-concepts/references/masking.md
(Graphics as a stencil mask),
pixijs-filters
(effects),
pixijs-performance
(batching,
cacheAsTexture
).
ts
const g = new Graphics();

g.rect(10, 10, 200, 100)
  .fill({ color: 0x3498db, alpha: 0.8 })
  .stroke({ width: 3, color: 0x2c3e50 });

g.circle(300, 60, 40).fill(0xe74c3c);

g.moveTo(50, 200)
  .lineTo(200, 200)
  .bezierCurveTo(250, 250, 100, 300, 50, 250)
  .closePath()
  .fill(0x6c5ce7);

app.stage.addChild(g);
相关技能:
pixijs-scene-core-concepts
(场景图基础)、
pixijs-scene-container
(将图形与其他对象分组)、
pixijs-scene-core-concepts/references/masking.md
(将Graphics用作模板遮罩)、
pixijs-filters
(特效)、
pixijs-performance
(批处理、
cacheAsTexture
)。

Constructor options

构造函数选项

All
Container
options (
position
,
scale
,
tint
,
label
,
filters
,
zIndex
, etc.) are also valid here — see
skills/pixijs-scene-core-concepts/references/constructor-options.md
.
Leaf-specific options added by
GraphicsOptions
:
OptionTypeDefaultDescription
context
GraphicsContext
new
GraphicsContext()
Shared drawing context. Passing a context reuses its tessellated geometry across multiple
Graphics
nodes, avoiding duplicate GPU work. If omitted, each
Graphics
creates and owns a new context.
roundPixels
boolean
false
Rounds the final on-screen
x
/
y
to the nearest pixel. Produces crisper lines for pixel-art styles at the cost of smooth sub-pixel movement.
The constructor also accepts a
GraphicsContext
instance as its sole argument (
new Graphics(ctx)
), which is shorthand for
new Graphics({ context: ctx })
.
所有
Container
选项(
position
scale
tint
label
filters
zIndex
等)在此处同样有效——详见
skills/pixijs-scene-core-concepts/references/constructor-options.md
GraphicsOptions
新增的叶子节点专属选项:
选项类型默认值说明
context
GraphicsContext
new
GraphicsContext()
共享的绘制上下文。传入上下文可在多个
Graphics
节点之间复用其细分后的几何图形,避免重复的GPU计算。若省略该选项,每个
Graphics
都会创建并拥有一个新的上下文。
roundPixels
boolean
false
将最终屏幕上的
x
/
y
坐标四舍五入到最近的像素。以牺牲平滑的亚像素移动为代价,为像素艺术风格生成更清晰的线条。
构造函数也可仅接受一个
GraphicsContext
实例作为参数(
new Graphics(ctx)
),这是
new Graphics({ context: ctx })
的简写形式。

Core Patterns

核心模式

Shape-then-fill workflow

先绘形状再填充的工作流

ts
const g = new Graphics();

g.rect(10, 10, 200, 100)
  .fill({ color: 0x3498db, alpha: 0.8 })
  .stroke({ width: 3, color: 0x2c3e50 });

g.circle(150, 200, 40).fill(0xe74c3c);
g.roundRect(300, 10, 150, 80, 12).fill(0x2ecc71);
g.poly([0, 0, 60, 0, 30, 50], true).fill(0x9b59b6);
g.star(400, 200, 5, 40, 20, 0).fill(0xf39c12);
g.ellipse(100, 350, 60, 30).fill(0x1abc9c);
fill()
accepts a
FillInput
: a color number/string,
{ color, alpha, texture, matrix, textureSpace }
, a
FillGradient
, a
FillPattern
, or a
Texture
. When filling with a texture,
textureSpace
controls coordinate mapping:
  • 'local'
    (default): texture is scaled to fit each shape's bounding box (normalized 0-1 coordinates).
  • 'global'
    : texture position/scale are relative to the Graphics object's coordinate system, shared across all shapes.
FillInput
also supports a nested
fill
subfield: a
FillStyle
options object can embed a
FillGradient
or
FillPattern
under its
fill
key, which applies the gradient or pattern alongside the
color
,
alpha
,
texture
, and
matrix
modifiers on the outer object.
stroke()
accepts a color, a
FillGradient
, a
FillPattern
, or a
StrokeStyle
object that combines all
FillStyle
keys (
color
,
alpha
,
texture
,
matrix
,
fill
,
textureSpace
) with stroke attributes:
AttributeDefaultNotes
width
1
Pixel width of the stroke.
cap
'butt'
One of
'butt'
,
'round'
,
'square'
. End style for open paths.
join
'miter'
One of
'miter'
,
'round'
,
'bevel'
. Corner style.
miterLimit
10
Caps how far miter joins extend before falling back to bevel.
alignment
0.5
1
= inside the shape,
0.5
= centered,
0
= outside.
pixelLine
false
Aligns 1-pixel lines to the pixel grid for crisp output. Graphics-only.
Strokes can use the same gradients and patterns as fills via
fill: gradient
or
texture: tex
:
ts
const grad = new FillGradient({
  end: { x: 1, y: 0 },
  colorStops: [
    { offset: 0, color: 0xff0000 },
    { offset: 1, color: 0x0000ff },
  ],
});
g.rect(0, 0, 200, 100).stroke({
  width: 8,
  fill: grad,
  join: "round",
  cap: "round",
});
Both
fill()
and
stroke()
can be called after the same shape; calling
stroke()
immediately after
fill()
reuses the same path.
ts
const g = new Graphics();

g.rect(10, 10, 200, 100)
  .fill({ color: 0x3498db, alpha: 0.8 })
  .stroke({ width: 3, color: 0x2c3e50 });

g.circle(150, 200, 40).fill(0xe74c3c);
g.roundRect(300, 10, 150, 80, 12).fill(0x2ecc71);
g.poly([0, 0, 60, 0, 30, 50], true).fill(0x9b59b6);
g.star(400, 200, 5, 40, 20, 0).fill(0xf39c12);
g.ellipse(100, 350, 60, 30).fill(0x1abc9c);
fill()
接受
FillInput
类型参数:颜色数值/字符串、
{ color, alpha, texture, matrix, textureSpace }
对象、
FillGradient
FillPattern
Texture
。使用纹理填充时,
textureSpace
控制坐标映射:
  • 'local'
    (默认):纹理缩放以适配每个形状的边界框(归一化0-1坐标)。
  • 'global'
    :纹理的位置/缩放相对于Graphics对象的坐标系,在所有形状之间共享。
FillInput
还支持嵌套的
fill
子字段:
FillStyle
选项对象可在其
fill
键下嵌入
FillGradient
FillPattern
,这样渐变或图案会与外层对象的
color
alpha
texture
matrix
修饰符一起生效。
stroke()
接受颜色、
FillGradient
FillPattern
,或结合所有
FillStyle
键(
color
alpha
texture
matrix
fill
textureSpace
)与描边属性的
StrokeStyle
对象:
属性默认值说明
width
1
描边的像素宽度。
cap
'butt'
可选值为
'butt'
'round'
'square'
。开放路径的端点样式。
join
'miter'
可选值为
'miter'
'round'
'bevel'
。拐角样式。
miterLimit
10
限制斜接拐角延伸的最大长度,超出后将退化为斜切拐角。
alignment
0.5
1
= 形状内部,
0.5
= 居中,
0
= 形状外部。
pixelLine
false
将1像素线条对齐到像素网格以生成清晰的输出。仅适用于Graphics。
描边可通过
fill: gradient
texture: tex
使用与填充相同的渐变和图案:
ts
const grad = new FillGradient({
  end: { x: 1, y: 0 },
  colorStops: [
    { offset: 0, color: 0xff0000 },
    { offset: 1, color: 0x0000ff },
  ],
});
g.rect(0, 0, 200, 100).stroke({
  width: 8,
  fill: grad,
  join: "round",
  cap: "round",
});
同一个形状绘制完成后,可同时调用
fill()
stroke()
;在
fill()
后立即调用
stroke()
会复用同一路径。

Advanced shape primitives

高级形状图元

ts
g.regularPoly(100, 100, 50, 6, 0).fill(0x3498db);
g.roundPoly(250, 100, 50, 5, 10).fill(0xe74c3c);
g.chamferRect(350, 50, 100, 80, 15).fill(0x2ecc71);
g.filletRect(500, 50, 100, 80, 15).fill(0x9b59b6);
g.roundShape(
  [
    { x: 50, y: 250, radius: 20 },
    { x: 150, y: 250, radius: 5 },
    { x: 150, y: 350, radius: 10 },
    { x: 50, y: 350, radius: 15 },
  ],
  10,
).fill(0xf39c12);
ts
g.regularPoly(100, 100, 50, 6, 0).fill(0x3498db);
g.roundPoly(250, 100, 50, 5, 10).fill(0xe74c3c);
g.chamferRect(350, 50, 100, 80, 15).fill(0x2ecc71);
g.filletRect(500, 50, 100, 80, 15).fill(0x9b59b6);
g.roundShape(
  [
    { x: 50, y: 250, radius: 20 },
    { x: 150, y: 250, radius: 5 },
    { x: 150, y: 350, radius: 10 },
    { x: 50, y: 350, radius: 15 },
  ],
  10,
).fill(0xf39c12);

Holes with cut()

使用cut()创建孔洞

ts
g.rect(0, 0, 200, 200).fill(0x00ff00).circle(100, 100, 50).cut();
cut()
subtracts the current active path from the previously drawn fill or stroke. Rules:
  • The hole must be completely inside the target shape. Holes that overlap edges or sit outside the shape will not render correctly because the renderer triangulates with the hole as an interior boundary.
  • cut()
    looks back at up to the last two instructions. When you
    fill()
    and then
    stroke()
    the same path, a single
    cut()
    adds the hole to the stroke first; a second
    cut()
    adds it to the fill underneath.
  • After
    cut()
    , the active path resets so you can start the next shape with
    moveTo
    ,
    rect
    , etc.
  • cut()
    applies to strokes too —
    g.rect(...).stroke(...).circle(...).cut()
    cuts a hole through the stroke outline.
Punch multiple holes with a single
cut()
by drawing several shapes into the active path before calling it. Each shape accumulates into the same hole path:
ts
const g = new Graphics();

g.rect(350, 350, 150, 150).fill(0x00ff00);

// Draw three circles into the active path, then cut them all in one call
g.circle(375, 375, 25);
g.circle(425, 425, 25);
g.circle(475, 475, 25);
g.cut();
If you need holes on separate filled shapes, give each shape its own
fill()
and matching
cut()
:
ts
g.rect(0, 0, 100, 100).fill(0x3498db);
g.circle(50, 50, 20).cut(); // hole in the rect

g.rect(120, 0, 100, 100).fill(0xe74c3c);
g.circle(170, 50, 20).cut(); // hole in the second rect
Calling
cut()
on a shape that already has a hole adds to the existing hole path rather than replacing it. Use this to layer holes additively.
ts
g.rect(0, 0, 200, 200).fill(0x00ff00).circle(100, 100, 50).cut();
cut()
会从之前绘制的填充或描边中减去当前活动路径。规则如下:
  • 孔洞必须完全位于目标形状内部。若孔洞与形状边缘重叠或位于形状外部,渲染会出现异常,因为渲染器会将孔洞视为内部边界进行三角化处理。
  • cut()
    会回溯最多最后两条指令。当你对同一路径先
    fill()
    stroke()
    时,单次
    cut()
    会先在描边中添加孔洞;第二次
    cut()
    会在下方的填充中添加孔洞。
  • 调用
    cut()
    后,活动路径会重置,你可以使用
    moveTo
    rect
    等开始绘制下一个形状。
  • cut()
    也适用于描边——
    g.rect(...).stroke(...).circle(...).cut()
    会在描边轮廓中裁剪出孔洞。
在调用
cut()
之前,可在活动路径中绘制多个形状,从而通过单次
cut()
创建多个孔洞。每个形状会累积到同一条孔洞路径中:
ts
const g = new Graphics();

g.rect(350, 350, 150, 150).fill(0x00ff00);

// 在活动路径中绘制三个圆形,然后通过一次调用裁剪所有孔洞
g.circle(375, 375, 25);
g.circle(425, 425, 25);
g.circle(475, 475, 25);
g.cut();
若需要在不同的填充形状上添加孔洞,请为每个形状单独调用
fill()
和对应的
cut()
ts
g.rect(0, 0, 100, 100).fill(0x3498db);
g.circle(50, 50, 20).cut(); // 矩形中的孔洞

g.rect(120, 0, 100, 100).fill(0xe74c3c);
g.circle(170, 50, 20).cut(); // 第二个矩形中的孔洞
对已有孔洞的形状调用
cut()
添加到现有孔洞路径中,而非替换。可通过这种方式叠加多个孔洞。

Paths and complex shapes

路径与复杂形状

ts
g.moveTo(50, 50)
  .lineTo(200, 50)
  .bezierCurveTo(250, 100, 250, 150, 200, 200)
  .quadraticCurveTo(100, 250, 50, 200)
  .closePath()
  .fill({ color: 0x6c5ce7, alpha: 0.7 })
  .stroke({ width: 2, color: 0xdfe6e9 });
Path methods:
moveTo
,
lineTo
,
bezierCurveTo
,
quadraticCurveTo
,
arc
,
arcTo
,
arcToSvg
,
closePath
. Call
beginPath()
to discard the current path and start a new one.
ts
// arc(cx, cy, radius, startAngle, endAngle, counterclockwise?)
g.moveTo(80, 50)
  .arc(50, 50, 30, 0, Math.PI)
  .stroke({ width: 4, color: 0x2c3e50 });

// arcTo(x1, y1, x2, y2, radius) — rounded corner between two line segments
g.moveTo(150, 20)
  .arcTo(200, 20, 200, 80, 20)
  .lineTo(200, 80)
  .stroke({ width: 2 });

// arcToSvg(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) — matches the SVG `A` command
g.moveTo(250, 50).arcToSvg(40, 20, 0, 1, 0, 330, 50).stroke({ width: 2 });
ts
g.moveTo(50, 50)
  .lineTo(200, 50)
  .bezierCurveTo(250, 100, 250, 150, 200, 200)
  .quadraticCurveTo(100, 250, 50, 200)
  .closePath()
  .fill({ color: 0x6c5ce7, alpha: 0.7 })
  .stroke({ width: 2, color: 0xdfe6e9 });
路径方法包括:
moveTo
lineTo
bezierCurveTo
quadraticCurveTo
arc
arcTo
arcToSvg
closePath
。调用
beginPath()
可丢弃当前路径并开始新路径。
ts
// arc(cx, cy, radius, startAngle, endAngle, counterclockwise?)
g.moveTo(80, 50)
  .arc(50, 50, 30, 0, Math.PI)
  .stroke({ width: 4, color: 0x2c3e50 });

// arcTo(x1, y1, x2, y2, radius) — 两条线段之间的圆角拐角
g.moveTo(150, 20)
  .arcTo(200, 20, 200, 80, 20)
  .lineTo(200, 80)
  .stroke({ width: 2 });

// arcToSvg(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, x, y) — 匹配SVG的`A`命令
g.moveTo(250, 50).arcToSvg(40, 20, 0, 1, 0, 330, 50).stroke({ width: 2 });

Gradients and patterns

渐变与图案

ts
// Linear gradient
const linear = new FillGradient({
  end: { x: 1, y: 0 },
  colorStops: [
    { offset: 0, color: 0xff0000 },
    { offset: 1, color: 0x0000ff },
  ],
});
g.rect(0, 0, 200, 100).fill(linear);

// Radial gradient — inner circle at center, outer circle reaches edges
const radial = new FillGradient({
  type: "radial",
  center: { x: 100, y: 100 },
  innerRadius: 0,
  outerCenter: { x: 100, y: 100 },
  outerRadius: 100,
  colorStops: [
    { offset: 0, color: 0xffffff },
    { offset: 1, color: 0x000000 },
  ],
});
g.circle(100, 100, 100).fill(radial);

const brick = await Assets.load("brick.png");
const pattern = new FillPattern(brick, "repeat"); // 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat'
g.rect(0, 120, 200, 100).fill(pattern);
FillGradient
's default
type
is
'linear'
with
start {0,0}
to
end {0,1}
. Set
type: 'radial'
with
center
/
innerRadius
and
outerCenter
/
outerRadius
for radial gradients.
FillPattern
's second argument selects a repetition mode and exposes
setTransform(matrix)
to scale, rotate, or offset the texture inside the pattern.
ts
// 线性渐变
const linear = new FillGradient({
  end: { x: 1, y: 0 },
  colorStops: [
    { offset: 0, color: 0xff0000 },
    { offset: 1, color: 0x0000ff },
  ],
});
g.rect(0, 0, 200, 100).fill(linear);

// 径向渐变 — 内圆在中心,外圆延伸至边缘
const radial = new FillGradient({
  type: "radial",
  center: { x: 100, y: 100 },
  innerRadius: 0,
  outerCenter: { x: 100, y: 100 },
  outerRadius: 100,
  colorStops: [
    { offset: 0, color: 0xffffff },
    { offset: 1, color: 0x000000 },
  ],
});
g.circle(100, 100, 100).fill(radial);

const brick = await Assets.load("brick.png");
const pattern = new FillPattern(brick, "repeat"); // 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat'
g.rect(0, 120, 200, 100).fill(pattern);
FillGradient
的默认
type
'linear'
,起始点为
{0,0}
,结束点为
{0,1}
。设置
type: 'radial'
并指定
center
/
innerRadius
outerCenter
/
outerRadius
可创建径向渐变。
FillPattern
的第二个参数选择重复模式,还可通过
setTransform(matrix)
缩放、旋转或偏移图案中的纹理。

Drawing a texture directly

直接绘制纹理

ts
const tex = await Assets.load("icon.png");

// Draw the whole texture at (x, y) with optional tint
g.texture(tex, 0xffffff, 20, 20);

// Draw a subregion (dx, dy, dw, dh)
g.texture(tex, 0xff0000, 100, 20, 64, 64);
Graphics.texture(texture, tint?, dx?, dy?, dw?, dh?)
is a shortcut for drawing a single textured rect without going through
fill()
. Useful for icons where you don't need the full sprite lifecycle.
ts
const tex = await Assets.load("icon.png");

// 在(x, y)位置绘制完整纹理,可指定色调
g.texture(tex, 0xffffff, 20, 20);

// 绘制纹理的子区域(dx, dy, dw, dh)
g.texture(tex, 0xff0000, 100, 20, 64, 64);
Graphics.texture(texture, tint?, dx?, dy?, dw?, dh?)
是无需通过
fill()
即可绘制单个带纹理矩形的快捷方式。适用于不需要完整精灵生命周期的图标绘制场景。

GraphicsContext sharing

GraphicsContext共享

ts
const ctx = new GraphicsContext().rect(0, 0, 50, 50).fill(0xff0000);

const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);
g2.x = 100;
Context sharing avoids duplicate GPU geometry; the expensive tessellation runs once. You can also assign a context after construction:
g.context = existingContext
.
ts
const ctx = new GraphicsContext().rect(0, 0, 50, 50).fill(0xff0000);

const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);
g2.x = 100;
上下文共享可避免重复的GPU几何计算;耗时的三角化处理仅需执行一次。你也可在构造完成后分配上下文:
g.context = existingContext

SVG import and export

SVG导入与导出

Parse SVG markup into the active context with
svg()
:
ts
g.svg(`<svg viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" fill="red"/>
</svg>`);
svg()
supports paths, basic shapes, and inline styles; complex hole geometries may render inaccurately because Pixi's triangulation is performance-optimized.
Serialize a
Graphics
or
GraphicsContext
back to a self-contained SVG document string with
graphicsContextToSvg
:
ts
import { Graphics, graphicsContextToSvg } from "pixi.js";

const g = new Graphics()
  .rect(0, 0, 100, 50)
  .fill({ color: 0xff0000 })
  .circle(150, 25, 25)
  .stroke({ color: 0x0000ff, width: 4 });

const svgString = graphicsContextToSvg(g, 2);
graphicsContextToSvg(source, precision = 2)
is a pure function that reads the context's instructions and returns a complete
<svg>
string with an auto-computed
viewBox
. Pass a
Graphics
or a
GraphicsContext
;
precision
controls decimal places on emitted coordinates. Exports every shape-then-fill primitive (advanced ones like
regularPoly
/
filletRect
fall back to a shape-path), all path methods, stroke attributes (
width
,
cap
,
join
,
miterLimit
),
fill-opacity
/
stroke-opacity
, and
FillGradient
(linear and radial) via a
<defs>
block. Holes collapse into one
<path>
with
fill-rule="evenodd"
.
FillPattern
and texture fills have no SVG equivalent: patterns fall through to the fill's solid
color
, and
texture()
instructions are skipped entirely. Exported markup roundtrips back through
g.svg(...)
without cleanup, so you can export, store, and later reimport a shape into another
Graphics
.
使用
svg()
将SVG标记解析到活动上下文中:
ts
g.svg(`<svg viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" fill="red"/>
</svg>`);
svg()
支持路径、基础形状和内联样式;复杂的孔洞几何图形可能渲染不准确,因为Pixi的三角化处理是针对性能优化的。
使用
graphicsContextToSvg
Graphics
GraphicsContext
序列化为独立的SVG文档字符串:
ts
import { Graphics, graphicsContextToSvg } from "pixi.js";

const g = new Graphics()
  .rect(0, 0, 100, 50)
  .fill({ color: 0xff0000 })
  .circle(150, 25, 25)
  .stroke({ color: 0x0000ff, width: 4 });

const svgString = graphicsContextToSvg(g, 2);
graphicsContextToSvg(source, precision = 2)
是一个纯函数,它读取上下文的指令并返回完整的
<svg>
字符串,其中包含自动计算的
viewBox
。传入
Graphics
GraphicsContext
均可;
precision
控制输出坐标的小数位数。它会导出所有先绘形状再填充的图元(
regularPoly
/
filletRect
等高级图元会退化为形状路径)、所有路径方法、描边属性(
width
cap
join
miterLimit
)、
fill-opacity
/
stroke-opacity
,以及通过
<defs>
块定义的
FillGradient
(线性和径向)。孔洞会合并为单个
fill-rule="evenodd"
<path>
FillPattern
和纹理填充没有对应的SVG实现:图案会退化为填充的纯色,
texture()
指令会被完全跳过。导出的标记可直接通过
g.svg(...)
重新导入,无需清理,因此你可以导出、存储形状,之后再将其重新导入到另一个
Graphics
中。

Reusing a GraphicsPath

复用GraphicsPath

ts
const arrow = new GraphicsPath()
  .moveTo(0, 0)
  .lineTo(40, 0)
  .lineTo(40, -10)
  .lineTo(60, 10)
  .lineTo(40, 30)
  .lineTo(40, 20)
  .lineTo(0, 20)
  .closePath();

g.path(arrow).fill(0x3498db);
g.translateTransform(80, 0).path(arrow).fill(0xe74c3c);
Graphics.path(graphicsPath)
(and
GraphicsContext.path()
) appends a prebuilt
GraphicsPath
onto the active path. Build once, draw many times.
ts
const arrow = new GraphicsPath()
  .moveTo(0, 0)
  .lineTo(40, 0)
  .lineTo(40, -10)
  .lineTo(60, 10)
  .lineTo(40, 30)
  .lineTo(40, 20)
  .lineTo(0, 20)
  .closePath();

g.path(arrow).fill(0x3498db);
g.translateTransform(80, 0).path(arrow).fill(0xe74c3c);
Graphics.path(graphicsPath)
(以及
GraphicsContext.path()
)会将预构建的
GraphicsPath
追加到活动路径中。一次构建,多次绘制。

Draw-time transforms

绘制时变换

Graphics
has its own transform stack used while drawing that is separate from the
Container
transform applied to the rendered output. The drawing methods are renamed to avoid clashing with
Container.rotation
,
Container.scale
,
Container.position
:
Drawing transformContainer transform
g.rotateTransform(angle)
g.rotation
g.scaleTransform(x, y?)
g.scale.set(x, y)
g.translateTransform(x, y?)
g.position.set(x, y)
g.setTransform(matrix)
or
setTransform(a,b,c,d,tx,ty)
g.setFromMatrix(matrix)
g.transform(matrix)
or
transform(a,b,c,d,tx,ty)
n/a
g.getTransform()
/
g.resetTransform()
n/a
ts
const g = new Graphics();

g.translateTransform(100, 100)
  .rotateTransform(Math.PI / 4)
  .rect(-25, -25, 50, 50)
  .fill(0x3498db);

// The square is rotated 45 degrees as it is added to the geometry.
// Setting g.rotation later rotates the entire Graphics on screen.
The drawing transform affects every subsequent shape and path command added to the context. Use
save()
/
restore()
to scope it.
Graphics
拥有自己的变换栈,仅在绘制过程中使用,与应用于渲染输出的
Container
变换相互独立。绘制方法已重命名,以避免与
Container.rotation
Container.scale
Container.position
冲突:
绘制时变换Container变换
g.rotateTransform(angle)
g.rotation
g.scaleTransform(x, y?)
g.scale.set(x, y)
g.translateTransform(x, y?)
g.position.set(x, y)
g.setTransform(matrix)
setTransform(a,b,c,d,tx,ty)
g.setFromMatrix(matrix)
g.transform(matrix)
transform(a,b,c,d,tx,ty)
无对应项
g.getTransform()
/
g.resetTransform()
无对应项
ts
const g = new Graphics();

g.translateTransform(100, 100)
  .rotateTransform(Math.PI / 4)
  .rect(-25, -25, 50, 50)
  .fill(0x3498db);

// 正方形在添加到几何图形时已旋转45度。
// 之后设置g.rotation会在屏幕上旋转整个Graphics对象。
绘制时变换会影响后续添加到上下文的所有形状和路径命令。使用
save()
/
restore()
可限定其作用范围。

State save/restore

状态保存/恢复

ts
g.save();
g.translateTransform(100, 100);
g.rotateTransform(Math.PI / 4);
g.rect(0, 0, 50, 50).fill(0xff0000);
g.restore();
save()
pushes the drawing transform, fill style, and stroke style onto a stack;
restore()
pops them.
Graphics
exposes
save
/
restore
directly, mirroring the underlying
GraphicsContext
calls.
ts
g.save();
g.translateTransform(100, 100);
g.rotateTransform(Math.PI / 4);
g.rect(0, 0, 50, 50).fill(0xff0000);
g.restore();
save()
会将绘制变换、填充样式和描边样式推入栈中;
restore()
会将它们弹出栈。
Graphics
直接暴露
save
/
restore
方法,与底层
GraphicsContext
的调用保持一致。

Default styles via setFillStyle / setStrokeStyle

通过setFillStyle / setStrokeStyle设置默认样式

ts
g.setFillStyle({ color: 0x3498db, alpha: 0.8 }).setStrokeStyle({
  width: 2,
  color: 0x2c3e50,
});

g.rect(0, 0, 100, 100).fill().stroke();
g.circle(150, 50, 40).fill().stroke();
setFillStyle()
and
setStrokeStyle()
configure the default style used by subsequent
fill()
/
stroke()
calls when no argument is passed. Read or replace the current style at any time via the
fillStyle
and
strokeStyle
getters/setters. Override the library-wide defaults by mutating
GraphicsContext.defaultFillStyle
and
GraphicsContext.defaultStrokeStyle
once at startup.
ts
g.setFillStyle({ color: 0x3498db, alpha: 0.8 }).setStrokeStyle({
  width: 2,
  color: 0x2c3e50,
});

g.rect(0, 0, 100, 100).fill().stroke();
g.circle(150, 50, 40).fill().stroke();
setFillStyle()
setStrokeStyle()
配置后续无参数调用
fill()
/
stroke()
时使用的默认样式。可随时通过
fillStyle
strokeStyle
getter/setter读取或替换当前样式。在启动时修改
GraphicsContext.defaultFillStyle
GraphicsContext.defaultStrokeStyle
可覆盖库级默认值。

Hit testing

命中测试

ts
const g = new Graphics().star(100, 100, 5, 60, 30).fill(0xf39c12);
g.eventMode = "static";
g.on("pointermove", (e) => {
  if (g.containsPoint(g.toLocal(e.global))) {
    /* over the star, not just its bbox */
  }
});
Graphics.containsPoint(pointInLocalSpace)
runs a topology-aware test against every filled and stroked shape in the context, including holes. Convert global pointer coordinates with
toLocal()
first.
ts
const g = new Graphics().star(100, 100, 5, 60, 30).fill(0xf39c12);
g.eventMode = "static";
g.on("pointermove", (e) => {
  if (g.containsPoint(g.toLocal(e.global))) {
    /* 鼠标悬停在星形上,而非仅其边界框 */
  }
});
Graphics.containsPoint(pointInLocalSpace)
会对上下文中所有填充和描边的形状(包括孔洞)进行拓扑感知测试。请先使用
toLocal()
将全局指针坐标转换为局部坐标。

Cloning, clearing, and bounds

克隆、清除与边界

ts
const g = new Graphics().rect(0, 0, 100, 100).fill(0xff0000);

const shallow = g.clone(); // shares the same GraphicsContext
const deep = g.clone(true); // creates an independent context

console.log(g.bounds.width); // 100 - geometry bounds before transforms

g.clear(); // wipes active path, instructions, and transform; fill/stroke styles persist
  • clone()
    returns a new
    Graphics
    that shares the source context (cheap, geometry is reused). Both objects update together if the context changes.
  • clone(true)
    clones the context as well so the new
    Graphics
    can be edited independently.
  • bounds
    returns the geometry bounds before the
    Container
    transform. Useful for layout decisions.
  • clear()
    resets the context so the same
    Graphics
    can be reused. See Common Mistakes below for guidance on when to clear versus when to keep stable geometry.
ts
const g = new Graphics().rect(0, 0, 100, 100).fill(0xff0000);

const shallow = g.clone(); // 共享同一个GraphicsContext
const deep = g.clone(true); // 创建独立的上下文

console.log(g.bounds.width); // 100 - 变换前的几何边界

g.clear(); // 清除活动路径、指令和变换;填充/描边样式保留
  • clone()
    返回一个新的
    Graphics
    ,它与源实例共享上下文(开销小,几何图形可复用)。若上下文发生变化,两个对象会同步更新。
  • clone(true)
    会同时克隆上下文,因此新的
    Graphics
    可独立编辑。
  • bounds
    返回
    Container
    变换前的几何边界。适用于布局决策。
  • clear()
    会重置上下文,以便复用同一个
    Graphics
    。请参考下方的常见错误,了解何时清除、何时保留稳定的几何图形。

GraphicsContext utilities

GraphicsContext工具方法

MemberBehavior
ctx.path(graphicsPath)
Apply a prebuilt
GraphicsPath
onto the active path. Reuse one path across many contexts or frames.
ctx.beginPath()
Discard the current active path and start a new one without affecting committed instructions.
ctx.setFillStyle(style)
/
ctx.fillStyle
Set or read the default fill style used by subsequent shapes without calling
fill()
.
ctx.setStrokeStyle(style)
/
ctx.strokeStyle
Set or read the default stroke style used by subsequent shapes without calling
stroke()
.
ctx.bounds
Cached geometry bounds across all fill/stroke/texture instructions.
ctx.clear()
Wipe instructions, the active path, and the drawing transform.
ctx.clone()
Deep copy including instructions, active path, transform, styles, and stack.
ctx.containsPoint(point)
Topology-aware hit test against all filled and stroked shapes (including holes).
ctx.batchMode
One of
'auto'
,
'batch'
,
'no-batch'
— force or disable batching for the shapes in this context.
ctx.customShader
Assign a
Shader
to override the default graphics shader.
GraphicsContext.defaultFillStyle
Static fallback used when
fill()
is called without arguments and no fill style is set.
GraphicsContext.defaultStrokeStyle
Static fallback used when
stroke()
is called without arguments and no stroke style is set.
GraphicsContext
is an
EventEmitter
that emits
update
,
destroy
, and
unload
events. Subscribe via
ctx.on('update' | 'destroy' | 'unload', cb)
when tooling or pools need to react to context lifecycle changes.
成员行为
ctx.path(graphicsPath)
将预构建的
GraphicsPath
应用到活动路径中。可在多个上下文或帧之间复用同一路径。
ctx.beginPath()
丢弃当前活动路径并开始新路径,不会影响已提交的指令。
ctx.setFillStyle(style)
/
ctx.fillStyle
设置或读取后续形状默认使用的填充样式,无需调用
fill()
ctx.setStrokeStyle(style)
/
ctx.strokeStyle
设置或读取后续形状默认使用的描边样式,无需调用
stroke()
ctx.bounds
缓存所有填充/描边/纹理指令的几何边界。
ctx.clear()
清除指令、活动路径和绘制变换。
ctx.clone()
深度复制,包括指令、活动路径、变换、样式和栈。
ctx.containsPoint(point)
对所有填充和描边的形状(包括孔洞)进行拓扑感知命中测试。
ctx.batchMode
可选值为
'auto'
'batch'
'no-batch'
—— 强制启用或禁用此上下文中形状的批处理。
ctx.customShader
分配
Shader
以覆盖默认的图形着色器。
GraphicsContext.defaultFillStyle
静态回退样式,当无参数调用
fill()
且未设置填充样式时使用。
GraphicsContext.defaultStrokeStyle
静态回退样式,当无参数调用
stroke()
且未设置描边样式时使用。
GraphicsContext
EventEmitter
,会发出
update
destroy
unload
事件。当工具或对象池需要响应上下文生命周期变化时,可通过
ctx.on('update' | 'destroy' | 'unload', cb)
订阅。

Common Mistakes

常见错误

[CRITICAL] Using v7 beginFill/drawRect/endFill

[严重] 使用v7的beginFill/drawRect/endFill

Wrong:
ts
const g = new Graphics().beginFill(0xff0000).drawRect(0, 0, 100, 100).endFill();
Correct:
ts
const g = new Graphics().rect(0, 0, 100, 100).fill(0xff0000);
v8 replaced "set style, draw, end" with "draw shape, then apply style".
beginFill
/
endFill
do not exist.
错误写法:
ts
const g = new Graphics().beginFill(0xff0000).drawRect(0, 0, 100, 100).endFill();
正确写法:
ts
const g = new Graphics().rect(0, 0, 100, 100).fill(0xff0000);
v8将「设置样式→绘制→结束」模式替换为「绘制形状→应用样式」。
beginFill
/
endFill
已不存在。

[CRITICAL] Using old shape method names

[严重] 使用旧的形状方法名称

Wrong:
ts
g.drawCircle(50, 50, 25);
Correct:
ts
g.circle(50, 50, 25);
All
draw*
methods were renamed in v8:
drawRect
rect
,
drawCircle
circle
,
drawEllipse
ellipse
,
drawPolygon
poly
,
drawRoundedRect
roundRect
,
drawStar
star
.
错误写法:
ts
g.drawCircle(50, 50, 25);
正确写法:
ts
g.circle(50, 50, 25);
v8中所有
draw*
方法均已重命名:
drawRect
rect
drawCircle
circle
drawEllipse
ellipse
drawPolygon
poly
drawRoundedRect
roundRect
drawStar
star

[CRITICAL] Using lineStyle instead of stroke

[严重] 使用lineStyle而非stroke

Wrong:
ts
g.lineStyle(2, 0xffffff);
g.drawRect(0, 0, 100, 100);
Correct:
ts
g.rect(0, 0, 100, 100).stroke({ width: 2, color: 0xffffff });
lineStyle
was removed. Use
stroke()
after drawing the shape. The stroke options object accepts
width
,
color
,
alpha
,
cap
,
join
,
alignment
,
miterLimit
, and
pixelLine
.
错误写法:
ts
g.lineStyle(2, 0xffffff);
g.drawRect(0, 0, 100, 100);
正确写法:
ts
g.rect(0, 0, 100, 100).stroke({ width: 2, color: 0xffffff });
lineStyle
已被移除。请在绘制形状后使用
stroke()
。描边选项对象接受
width
color
alpha
cap
join
alignment
miterLimit
pixelLine

[HIGH] Using beginHole/endHole for holes

[高风险] 使用beginHole/endHole创建孔洞

Wrong:
ts
g.beginFill(0x00ff00)
  .drawRect(0, 0, 100, 100)
  .beginHole()
  .drawCircle(50, 50, 20)
  .endHole()
  .endFill();
Correct:
ts
g.rect(0, 0, 100, 100).fill(0x00ff00).circle(50, 50, 20).cut();
beginHole
/
endHole
were replaced by
cut()
. Draw the outer shape, fill it, then draw the hole shape and call
cut()
.
错误写法:
ts
g.beginFill(0x00ff00)
  .drawRect(0, 0, 100, 100)
  .beginHole()
  .drawCircle(50, 50, 20)
  .endHole()
  .endFill();
正确写法:
ts
g.rect(0, 0, 100, 100).fill(0x00ff00).circle(50, 50, 20).cut();
beginHole
/
endHole
已被
cut()
取代。先绘制外部形状并填充,然后绘制孔洞形状并调用
cut()

[HIGH] Using GraphicsGeometry instead of GraphicsContext

[高风险] 使用GraphicsGeometry而非GraphicsContext

Wrong:
ts
const geom = g.geometry;
const clone = new Graphics(geom);
Correct:
ts
const ctx = new GraphicsContext().rect(0, 0, 100, 100).fill(0xff0000);
const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);
GraphicsGeometry
was replaced by
GraphicsContext
in v8. There is no
.geometry
property.
错误写法:
ts
const geom = g.geometry;
const clone = new Graphics(geom);
正确写法:
ts
const ctx = new GraphicsContext().rect(0, 0, 100, 100).fill(0xff0000);
const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);
v8中
GraphicsGeometry
已被
GraphicsContext
取代。不再有
.geometry
属性。

[HIGH] Destroying a shared GraphicsContext unexpectedly

[高风险] 意外销毁共享的GraphicsContext

ts
const ctx = new GraphicsContext().rect(0, 0, 50, 50).fill(0xff0000);
const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);

g1.destroy({ context: true }); // also nullifies g2's context reference
Destroying a shared
GraphicsContext
does not destroy sharing instances but breaks them by nullifying their context reference. When passing a context via the constructor,
destroy()
with no args preserves the context; use
destroy({ context: false })
to be explicit. Only destroy the context when all sharing instances are done with it. A self-owned context (not passed via constructor) is still destroyed by
destroy()
with no args.
ts
const ctx = new GraphicsContext().rect(0, 0, 50, 50).fill(0xff0000);
const g1 = new Graphics(ctx);
const g2 = new Graphics(ctx);

g1.destroy({ context: true }); // 同时会使g2的上下文引用变为null
销毁共享的
GraphicsContext
不会销毁共享实例,但会通过将上下文引用设为null来破坏它们。当通过构造函数传入上下文时,无参数调用
destroy()
会保留上下文;使用
destroy({ context: false })
可明确指定保留上下文。仅当所有共享实例不再需要上下文时,才销毁它。自有的上下文(未通过构造函数传入)仍会被无参数的
destroy()
销毁。

[HIGH] Clearing and redrawing Graphics every frame

[高风险] 每帧都清除并重新绘制Graphics

Graphics are designed to be stable, not dynamic. Calling
clear()
and redrawing every frame rebuilds GPU geometry each time. For dynamic visuals:
  • Use
    Sprite
    with pre-rendered textures and transform changes.
  • Use
    cacheAsTexture(true)
    for complex static graphics.
  • For real-time shape changes, consider
    Mesh
    with custom geometry updates.
This is the opposite of HTML Canvas 2D, where redrawing each frame is normal. PixiJS tessellates shapes into GPU triangles, so initial draw is expensive but subsequent renders are fast. Treat
Graphics
more like SVG elements than canvas draw calls.
Graphics设计为稳定的图形元素,而非动态元素。每帧调用
clear()
并重新绘制会每次都重建GPU几何图形。如需动态视觉效果:
  • 使用
    Sprite
    结合预渲染纹理和变换修改。
  • 对复杂的静态图形使用
    cacheAsTexture(true)
  • 如需实时形状变化,可考虑使用
    Mesh
    并自定义几何图形更新。
这与HTML Canvas 2D相反,后者每帧重绘是常规操作。PixiJS会将形状细分为GPU三角形,因此初始绘制开销较大,但后续渲染速度很快。请将
Graphics
视为SVG元素而非Canvas绘制调用。

[MEDIUM] Do not nest children inside a Graphics

[中风险] 不要在Graphics中嵌套子元素

Graphics
sets
allowChildren = false
. Adding children logs a deprecation warning and will be a hard error in a future version. Wrap multiple graphics alongside other leaves in a plain
Container
:
ts
const group = new Container();
group.addChild(graphics, sprite);
Graphics
设置了
allowChildren = false
。添加子元素会记录弃用警告,未来版本会变为硬错误。请将多个图形与其他叶子元素一起包装在普通的
Container
中:
ts
const group = new Container();
group.addChild(graphics, sprite);

API Reference

API参考