pixijs-scene-graphics
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGraphicsrectcirclemoveTofillstrokethisGraphicsContextAssumes familiarity with . is a leaf: do not nest children inside it. Wrap multiple objects in a to group them.
pixijs-scene-core-conceptsGraphicsGraphicsContainerGraphicsrectcirclemoveTofillstrokethisGraphicsContext本文假设你已熟悉。是叶子节点:请勿在其中嵌套子元素。如需分组多个对象,请将它们包装在中。
pixijs-scene-core-conceptsGraphicsGraphicsContainerQuick 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: (scene graph basics), (group graphics with other objects), (Graphics as a stencil mask), (effects), (batching, ).
pixijs-scene-core-conceptspixijs-scene-containerpixijs-scene-core-concepts/references/masking.mdpixijs-filterspixijs-performancecacheAsTexturets
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);相关技能: (场景图基础)、(将图形与其他对象分组)、(将Graphics用作模板遮罩)、(特效)、(批处理、)。
pixijs-scene-core-conceptspixijs-scene-containerpixijs-scene-core-concepts/references/masking.mdpixijs-filterspixijs-performancecacheAsTextureConstructor options
构造函数选项
All options (, , , , , , etc.) are also valid here — see .
ContainerpositionscaletintlabelfilterszIndexskills/pixijs-scene-core-concepts/references/constructor-options.mdLeaf-specific options added by :
GraphicsOptions| Option | Type | Default | Description |
|---|---|---|---|
| | new | Shared drawing context. Passing a context reuses its tessellated geometry across multiple |
| | | Rounds the final on-screen |
The constructor also accepts a instance as its sole argument (), which is shorthand for .
GraphicsContextnew Graphics(ctx)new Graphics({ context: ctx })所有选项(、、、、、等)在此处同样有效——详见。
ContainerpositionscaletintlabelfilterszIndexskills/pixijs-scene-core-concepts/references/constructor-options.mdGraphicsOptions| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | new | 共享的绘制上下文。传入上下文可在多个 |
| | | 将最终屏幕上的 |
构造函数也可仅接受一个实例作为参数(),这是的简写形式。
GraphicsContextnew 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()FillInput{ color, alpha, texture, matrix, textureSpace }FillGradientFillPatternTexturetextureSpace- (default): texture is scaled to fit each shape's bounding box (normalized 0-1 coordinates).
'local' - : texture position/scale are relative to the Graphics object's coordinate system, shared across all shapes.
'global'
FillInputfillFillStyleFillGradientFillPatternfillcoloralphatexturematrixstroke()FillGradientFillPatternStrokeStyleFillStylecoloralphatexturematrixfilltextureSpace| Attribute | Default | Notes |
|---|---|---|
| | Pixel width of the stroke. |
| | One of |
| | One of |
| | Caps how far miter joins extend before falling back to bevel. |
| | |
| | Aligns 1-pixel lines to the pixel grid for crisp output. Graphics-only. |
Strokes can use the same gradients and patterns as fills via or :
fill: gradienttexture: texts
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 and can be called after the same shape; calling immediately after reuses the same path.
fill()stroke()stroke()fill()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 }FillGradientFillPatternTexturetextureSpace- (默认):纹理缩放以适配每个形状的边界框(归一化0-1坐标)。
'local' - :纹理的位置/缩放相对于Graphics对象的坐标系,在所有形状之间共享。
'global'
FillInputfillFillStylefillFillGradientFillPatterncoloralphatexturematrixstroke()FillGradientFillPatternFillStylecoloralphatexturematrixfilltextureSpaceStrokeStyle| 属性 | 默认值 | 说明 |
|---|---|---|
| | 描边的像素宽度。 |
| | 可选值为 |
| | 可选值为 |
| | 限制斜接拐角延伸的最大长度,超出后将退化为斜切拐角。 |
| | |
| | 将1像素线条对齐到像素网格以生成清晰的输出。仅适用于Graphics。 |
描边可通过或使用与填充相同的渐变和图案:
fill: gradienttexture: texts
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()- 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.
- looks back at up to the last two instructions. When you
cut()and thenfill()the same path, a singlestroke()adds the hole to the stroke first; a secondcut()adds it to the fill underneath.cut() - After , the active path resets so you can start the next shape with
cut(),moveTo, etc.rect - applies to strokes too —
cut()cuts a hole through the stroke outline.g.rect(...).stroke(...).circle(...).cut()
Punch multiple holes with a single by drawing several shapes into the active path before calling it. Each shape accumulates into the same hole path:
cut()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 and matching :
fill()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 rectCalling on a shape that already has a hole adds to the existing hole path rather than replacing it. Use this to layer holes additively.
cut()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: , , , , , , , . Call to discard the current path and start a new one.
moveTolineTobezierCurveToquadraticCurveToarcarcToarcToSvgclosePathbeginPath()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 });路径方法包括:、、、、、、、。调用可丢弃当前路径并开始新路径。
moveTolineTobezierCurveToquadraticCurveToarcarcToarcToSvgclosePathbeginPath()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);FillGradienttype'linear'start {0,0}end {0,1}type: 'radial'centerinnerRadiusouterCenterouterRadiusFillPatternsetTransform(matrix)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);FillGradienttype'linear'{0,0}{0,1}type: 'radial'centerinnerRadiusouterCenterouterRadiusFillPatternsetTransform(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?)fill()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 = existingContextts
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 = existingContextSVG 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()Serialize a or back to a self-contained SVG document string with :
GraphicsGraphicsContextgraphicsContextToSvgts
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>viewBoxGraphicsGraphicsContextprecisionregularPolyfilletRectwidthcapjoinmiterLimitfill-opacitystroke-opacityFillGradient<defs><path>fill-rule="evenodd"FillPatterncolortexture()g.svg(...)Graphics使用将SVG标记解析到活动上下文中:
svg()ts
g.svg(`<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="red"/>
</svg>`);svg()使用将或序列化为独立的SVG文档字符串:
graphicsContextToSvgGraphicsGraphicsContextts
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>viewBoxGraphicsGraphicsContextprecisionregularPolyfilletRectwidthcapjoinmiterLimitfill-opacitystroke-opacity<defs>FillGradientfill-rule="evenodd"<path>FillPatterntexture()g.svg(...)GraphicsReusing 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)GraphicsContext.path()GraphicsPathts
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()GraphicsPathDraw-time transforms
绘制时变换
GraphicsContainerContainer.rotationContainer.scaleContainer.position| Drawing transform | Container transform |
|---|---|
| |
| |
| |
| |
| n/a |
| 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 / to scope it.
save()restore()GraphicsContainerContainer.rotationContainer.scaleContainer.position| 绘制时变换 | Container变换 |
|---|---|
| |
| |
| |
| |
| 无对应项 |
| 无对应项 |
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()restore()GraphicssaverestoreGraphicsContextts
g.save();
g.translateTransform(100, 100);
g.rotateTransform(Math.PI / 4);
g.rect(0, 0, 50, 50).fill(0xff0000);
g.restore();save()restore()GraphicssaverestoreGraphicsContextDefault 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()setStrokeStyle()fill()stroke()fillStylestrokeStyleGraphicsContext.defaultFillStyleGraphicsContext.defaultStrokeStylets
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()fillStylestrokeStyleGraphicsContext.defaultFillStyleGraphicsContext.defaultStrokeStyleHit 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)toLocal()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- returns a new
clone()that shares the source context (cheap, geometry is reused). Both objects update together if the context changes.Graphics - clones the context as well so the new
clone(true)can be edited independently.Graphics - returns the geometry bounds before the
boundstransform. Useful for layout decisions.Container - resets the context so the same
clear()can be reused. See Common Mistakes below for guidance on when to clear versus when to keep stable geometry.Graphics
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工具方法
| Member | Behavior |
|---|---|
| Apply a prebuilt |
| Discard the current active path and start a new one without affecting committed instructions. |
| Set or read the default fill style used by subsequent shapes without calling |
| Set or read the default stroke style used by subsequent shapes without calling |
| Cached geometry bounds across all fill/stroke/texture instructions. |
| Wipe instructions, the active path, and the drawing transform. |
| Deep copy including instructions, active path, transform, styles, and stack. |
| Topology-aware hit test against all filled and stroked shapes (including holes). |
| One of |
| Assign a |
| Static fallback used when |
| Static fallback used when |
GraphicsContextEventEmitterupdatedestroyunloadctx.on('update' | 'destroy' | 'unload', cb)| 成员 | 行为 |
|---|---|
| 将预构建的 |
| 丢弃当前活动路径并开始新路径,不会影响已提交的指令。 |
| 设置或读取后续形状默认使用的填充样式,无需调用 |
| 设置或读取后续形状默认使用的描边样式,无需调用 |
| 缓存所有填充/描边/纹理指令的几何边界。 |
| 清除指令、活动路径和绘制变换。 |
| 深度复制,包括指令、活动路径、变换、样式和栈。 |
| 对所有填充和描边的形状(包括孔洞)进行拓扑感知命中测试。 |
| 可选值为 |
| 分配 |
| 静态回退样式,当无参数调用 |
| 静态回退样式,当无参数调用 |
GraphicsContextEventEmitterupdatedestroyunloadctx.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". / do not exist.
beginFillendFill错误写法:
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将「设置样式→绘制→结束」模式替换为「绘制形状→应用样式」。/已不存在。
beginFillendFill[CRITICAL] Using old shape method names
[严重] 使用旧的形状方法名称
Wrong:
ts
g.drawCircle(50, 50, 25);Correct:
ts
g.circle(50, 50, 25);All methods were renamed in v8: → , → , → , → , → , → .
draw*drawRectrectdrawCirclecircledrawEllipseellipsedrawPolygonpolydrawRoundedRectroundRectdrawStarstar错误写法:
ts
g.drawCircle(50, 50, 25);正确写法:
ts
g.circle(50, 50, 25);v8中所有方法均已重命名: → 、 → 、 → 、 → 、 → 、 → 。
draw*drawRectrectdrawCirclecircledrawEllipseellipsedrawPolygonpolydrawRoundedRectroundRectdrawStarstar[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 });lineStylestroke()widthcoloralphacapjoinalignmentmiterLimitpixelLine错误写法:
ts
g.lineStyle(2, 0xffffff);
g.drawRect(0, 0, 100, 100);正确写法:
ts
g.rect(0, 0, 100, 100).stroke({ width: 2, color: 0xffffff });lineStylestroke()widthcoloralphacapjoinalignmentmiterLimitpixelLine[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();beginHoleendHolecut()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();beginHoleendHolecut()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);GraphicsGeometryGraphicsContext.geometry错误写法:
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中已被取代。不再有属性。
GraphicsGeometryGraphicsContext.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 referenceDestroying a shared does not destroy sharing instances but breaks them by nullifying their context reference. When passing a context via the constructor, with no args preserves the context; use 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 with no args.
GraphicsContextdestroy()destroy({ context: false })destroy()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销毁共享的不会销毁共享实例,但会通过将上下文引用设为null来破坏它们。当通过构造函数传入上下文时,无参数调用会保留上下文;使用可明确指定保留上下文。仅当所有共享实例不再需要上下文时,才销毁它。自有的上下文(未通过构造函数传入)仍会被无参数的销毁。
GraphicsContextdestroy()destroy({ context: false })destroy()[HIGH] Clearing and redrawing Graphics every frame
[高风险] 每帧都清除并重新绘制Graphics
Graphics are designed to be stable, not dynamic. Calling and redrawing every frame rebuilds GPU geometry each time. For dynamic visuals:
clear()- Use with pre-rendered textures and transform changes.
Sprite - Use for complex static graphics.
cacheAsTexture(true) - For real-time shape changes, consider with custom geometry updates.
Mesh
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 more like SVG elements than canvas draw calls.
GraphicsGraphics设计为稳定的图形元素,而非动态元素。每帧调用并重新绘制会每次都重建GPU几何图形。如需动态视觉效果:
clear()- 使用结合预渲染纹理和变换修改。
Sprite - 对复杂的静态图形使用。
cacheAsTexture(true) - 如需实时形状变化,可考虑使用并自定义几何图形更新。
Mesh
这与HTML Canvas 2D相反,后者每帧重绘是常规操作。PixiJS会将形状细分为GPU三角形,因此初始绘制开销较大,但后续渲染速度很快。请将视为SVG元素而非Canvas绘制调用。
Graphics[MEDIUM] Do not nest children inside a Graphics
[中风险] 不要在Graphics中嵌套子元素
GraphicsallowChildren = falseContainerts
const group = new Container();
group.addChild(graphics, sprite);GraphicsallowChildren = falseContainerts
const group = new Container();
group.addChild(graphics, sprite);