graphics-and-shapes

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Phaser 4 — Graphics and Shapes

Phaser 4 — 图形与形状

Drawing primitives with the Graphics game object, and using Shape game objects (Arc, Curve, Ellipse, Grid, IsoBox, IsoTriangle, Line, Polygon, Rectangle, Star, Triangle).
Related skills: sprites-and-images.md, game-object-components.md

使用Graphics游戏对象绘制图元,以及使用Shape游戏对象(Arc、Curve、Ellipse、Grid、IsoBox、IsoTriangle、Line、Polygon、Rectangle、Star、Triangle)。
相关技能:sprites-and-images.md, game-object-components.md

Quick Start

快速入门

js
// Draw a filled rectangle and stroked circle with Graphics
const gfx = this.add.graphics();

gfx.fillStyle(0x00aa00, 1);
gfx.fillRect(50, 50, 200, 100);

gfx.lineStyle(3, 0xff0000, 1);
gfx.strokeCircle(400, 150, 60);
js
// Same shapes as standalone Shape game objects
const rect = this.add.rectangle(150, 100, 200, 100, 0x00aa00);
const circle = this.add.circle(400, 150, 60);
circle.setStrokeStyle(3, 0xff0000);

js
// 使用Graphics绘制填充矩形和描边圆形
const gfx = this.add.graphics();

gfx.fillStyle(0x00aa00, 1);
gfx.fillRect(50, 50, 200, 100);

gfx.lineStyle(3, 0xff0000, 1);
gfx.strokeCircle(400, 150, 60);
js
// 使用独立Shape游戏对象绘制相同形状
const rect = this.add.rectangle(150, 100, 200, 100, 0x00aa00);
const circle = this.add.circle(400, 150, 60);
circle.setStrokeStyle(3, 0xff0000);

Core Concepts — Graphics vs Shape Objects

核心概念 — Graphics与Shape对象

Phaser offers two approaches for rendering primitives without textures.
Phaser提供两种无需纹理即可渲染图元的方式。

Graphics Game Object

Graphics游戏对象

Created with
this.add.graphics()
. An imperative drawing surface — you call methods like
fillRect
,
strokeCircle
,
beginPath
/
lineTo
/
strokePath
to build up a command buffer that replays each frame.
  • Factory:
    this.add.graphics(config?)
    where config is
    { x?, y?, lineStyle?, fillStyle? }
    .
  • Supports paths, arcs, gradients, rounded rectangles, canvas transforms (
    translateCanvas
    ,
    scaleCanvas
    ,
    rotateCanvas
    ), and
    save
    /
    restore
    .
  • Can generate a Texture from the drawing via
    generateTexture(key, width, height)
    .
  • Expensive to render, especially with complex shapes. Uses its own WebGL shader. Group Graphics objects together to minimize batch flushes.
  • Components: AlphaSingle, BlendMode, Depth, Lighting, Mask, RenderNodes, Transform, Visible, ScrollFactor.
  • Does NOT include Origin or GetBounds (position is set via options or
    setPosition
    ).
通过
this.add.graphics()
创建。一种命令式绘制表面——你可以调用
fillRect
strokeCircle
beginPath
/
lineTo
/
strokePath
等方法来构建命令缓冲区,每帧都会重放这些命令。
  • 工厂方法:
    this.add.graphics(config?)
    ,其中config为
    { x?, y?, lineStyle?, fillStyle? }
  • 支持路径、圆弧、渐变、圆角矩形、画布变换(
    translateCanvas
    scaleCanvas
    rotateCanvas
    )以及
    save
    /
    restore
  • 可通过
    generateTexture(key, width, height)
    将绘制内容生成为Texture。
  • 渲染成本较高,尤其是复杂形状。使用独立的WebGL着色器。将Graphics对象分组以最小化批次刷新。
  • 组件:AlphaSingle、BlendMode、Depth、Lighting、Mask、RenderNodes、Transform、Visible、ScrollFactor。
  • 不包含Origin或GetBounds组件(位置通过配置项或
    setPosition
    设置)。

Shape Game Objects

Shape游戏对象

Individual game objects (Arc, Rectangle, Star, etc.) extending the base
Shape
class. Each renders one predefined geometric shape with precomputed path data.
  • Created via dedicated factory methods:
    this.add.rectangle(...)
    ,
    this.add.circle(...)
    , etc.
  • Fully featured game objects: can be tweened, scaled, added to groups/containers, enabled for input/physics.
  • Style via
    setFillStyle(color, alpha)
    and
    setStrokeStyle(lineWidth, color, alpha)
    .
  • Share the same WebGL batch as Graphics for efficient rendering.
  • Do NOT support gradients, path detail threshold, or canvas transforms.
  • Components: AlphaSingle, BlendMode, Depth, GetBounds, Lighting, Mask, Origin, RenderNodes, ScrollFactor, Transform, Visible.
  • Include Origin and GetBounds (unlike Graphics).
When to use which:
  • Use Graphics for dynamic drawing, complex paths, multiple shapes on one object, gradients, or generating textures.
  • Use Shape objects for individual UI elements, simple indicators, physics-enabled shapes, or anything that benefits from game object features (origin, bounds, input).

继承自基础
Shape
类的独立游戏对象(Arc、Rectangle、Star等)。每个对象渲染一个预定义的几何形状,带有预先计算的路径数据。
  • 通过专用工厂方法创建:
    this.add.rectangle(...)
    this.add.circle(...)
    等。
  • 功能完整的游戏对象:可补间动画、缩放、添加到组/容器、启用输入/物理系统。
  • 通过
    setFillStyle(color, alpha)
    setStrokeStyle(lineWidth, color, alpha)
    设置样式。
  • 与Graphics共享同一WebGL批次,实现高效渲染。
  • 不支持渐变、路径细节阈值或画布变换。
  • 组件:AlphaSingle、BlendMode、Depth、GetBounds、Lighting、Mask、Origin、RenderNodes、ScrollFactor、Transform、Visible。
  • 包含Origin和GetBounds组件(与Graphics不同)。
何时选择哪种方式:
  • 使用Graphics进行动态绘制、复杂路径、单个对象上的多个形状、渐变或生成纹理。
  • 使用Shape对象创建单个UI元素、简单指示器、支持物理系统的形状,或任何需要游戏对象特性(原点、边界、输入)的场景。

Common Patterns

常见模式

Fill and Stroke Styles (Graphics)

填充与描边样式(Graphics)

js
const gfx = this.add.graphics();

// Solid fill — call before any fill* method
gfx.fillStyle(0xff0000, 1);          // (color, alpha)

// Line style — call before any stroke* method
gfx.lineStyle(4, 0x00ff00, 1);       // (width, color, alpha)

// Gradient fill (WebGL only) — 4 corner colors
gfx.fillGradientStyle(
    0xff0000, 0x00ff00, 0x0000ff, 0xffff00,  // tl, tr, bl, br colors
    1, 1, 1, 1                                 // tl, tr, bl, br alphas
);
gfx.fillRect(0, 0, 300, 200);

// Gradient line style (WebGL only)
gfx.lineGradientStyle(2, 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 1);
js
const gfx = this.add.graphics();

// 纯色填充 — 在调用任何fill*方法前调用
gfx.fillStyle(0xff0000, 1);          // (颜色, 透明度)

// 线条样式 — 在调用任何stroke*方法前调用
gfx.lineStyle(4, 0x00ff00, 1);       // (宽度, 颜色, 透明度)

// 渐变填充(仅WebGL)— 四个角的颜色
gfx.fillGradientStyle(
    0xff0000, 0x00ff00, 0x0000ff, 0xffff00,  // 左上、右上、左下、右下颜色
    1, 1, 1, 1                                 // 左上、右上、左下、右下透明度
);
gfx.fillRect(0, 0, 300, 200);

// 渐变线条样式(仅WebGL)
gfx.lineGradientStyle(2, 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 1);

Drawing Primitives (Graphics)

绘制图元(Graphics)

js
const gfx = this.add.graphics();

// Rectangles
gfx.fillStyle(0x0000ff);
gfx.fillRect(x, y, width, height);
gfx.lineStyle(2, 0xffffff);
gfx.strokeRect(x, y, width, height);

// Circles
gfx.fillCircle(x, y, radius);
gfx.strokeCircle(x, y, radius);

// Ellipses
gfx.fillEllipse(x, y, width, height, smoothness);
gfx.strokeEllipse(x, y, width, height, smoothness);   // smoothness defaults to 32

// Triangles
gfx.fillTriangle(x0, y0, x1, y1, x2, y2);
gfx.strokeTriangle(x0, y0, x1, y1, x2, y2);

// Points (draws a small square)
gfx.fillPoint(x, y, size);                             // size defaults to 1

// Lines
gfx.lineBetween(x1, y1, x2, y2);
js
const gfx = this.add.graphics();

// 矩形
gfx.fillStyle(0x0000ff);
gfx.fillRect(x, y, width, height);
gfx.lineStyle(2, 0xffffff);
gfx.strokeRect(x, y, width, height);

// 圆形
gfx.fillCircle(x, y, radius);
gfx.strokeCircle(x, y, radius);

// 椭圆
gfx.fillEllipse(x, y, width, height, smoothness);
gfx.strokeEllipse(x, y, width, height, smoothness);   // smoothness默认值为32

// 三角形
gfx.fillTriangle(x0, y0, x1, y1, x2, y2);
gfx.strokeTriangle(x0, y0, x1, y1, x2, y2);

// 点(绘制小正方形)
gfx.fillPoint(x, y, size);                             // size默认值为1

// 线条
gfx.lineBetween(x1, y1, x2, y2);

Rounded Rectangles

圆角矩形

js
const gfx = this.add.graphics();

// Uniform radius (default 20)
gfx.fillStyle(0x333333);
gfx.fillRoundedRect(50, 50, 300, 200, 16);
gfx.lineStyle(2, 0xffffff);
gfx.strokeRoundedRect(50, 50, 300, 200, 16);

// Per-corner radius
gfx.fillRoundedRect(50, 50, 300, 200, {
    tl: 20, tr: 20, bl: 0, br: 0
});

// Concave corners (negative values)
gfx.fillRoundedRect(50, 50, 300, 200, { tl: -10, tr: -10, bl: -10, br: -10 });
js
const gfx = this.add.graphics();

// 统一圆角半径(默认20)
gfx.fillStyle(0x333333);
gfx.fillRoundedRect(50, 50, 300, 200, 16);
gfx.lineStyle(2, 0xffffff);
gfx.strokeRoundedRect(50, 50, 300, 200, 16);

// 每个角单独设置半径
gfx.fillRoundedRect(50, 50, 300, 200, {
    tl: 20, tr: 20, bl: 0, br: 0
});

// 凹角(负值)
gfx.fillRoundedRect(50, 50, 300, 200, { tl: -10, tr: -10, bl: -10, br: -10 });

Path Drawing

路径绘制

js
const gfx = this.add.graphics();

// Manual path
gfx.lineStyle(3, 0xffff00);
gfx.beginPath();
gfx.moveTo(100, 100);
gfx.lineTo(200, 50);
gfx.lineTo(300, 100);
gfx.lineTo(250, 200);
gfx.closePath();
gfx.strokePath();       // or gfx.stroke() — alias for strokePath

// Fill a path
gfx.fillStyle(0x00aaff);
gfx.beginPath();
gfx.moveTo(100, 100);
gfx.lineTo(200, 50);
gfx.lineTo(300, 100);
gfx.closePath();
gfx.fillPath();         // or gfx.fill() — alias for fillPath

// Arc within a path (angles in radians)
gfx.beginPath();
gfx.arc(200, 200, 80, 0, Math.PI / 2, false, 0);   // (x, y, radius, startAngle, endAngle, anticlockwise, overshoot)
gfx.strokePath();

// Pie slice
gfx.slice(200, 200, 80, 0, Math.PI / 3, false);     // auto begins/closes path
gfx.fillPath();

// Stroke/fill from point arrays
gfx.strokePoints(points, closeShape, closePath, endIndex);
gfx.fillPoints(points, closeShape, closePath, endIndex);
js
const gfx = this.add.graphics();

// 手动绘制路径
gfx.lineStyle(3, 0xffff00);
gfx.beginPath();
gfx.moveTo(100, 100);
gfx.lineTo(200, 50);
gfx.lineTo(300, 100);
gfx.lineTo(250, 200);
gfx.closePath();
gfx.strokePath();       // 或gfx.stroke() — strokePath的别名

// 填充路径
gfx.fillStyle(0x00aaff);
gfx.beginPath();
gfx.moveTo(100, 100);
gfx.lineTo(200, 50);
gfx.lineTo(300, 100);
gfx.closePath();
gfx.fillPath();         // 或gfx.fill() — fillPath的别名

// 路径中的圆弧(角度为弧度)
gfx.beginPath();
gfx.arc(200, 200, 80, 0, Math.PI / 2, false, 0);   // (x, y, 半径, 起始角度, 结束角度, 逆时针, 过冲值)
gfx.strokePath();

// 饼图切片
gfx.slice(200, 200, 80, 0, Math.PI / 3, false);     // 自动开始/闭合路径
ngfx.fillPath();

// 通过点数组描边/填充
gfx.strokePoints(points, closeShape, closePath, endIndex);
gfx.fillPoints(points, closeShape, closePath, endIndex);

Geom Shape Helpers

几何形状辅助方法

Graphics has convenience methods that accept Phaser.Geom objects directly:
js
const circle = new Phaser.Geom.Circle(200, 200, 50);
const rect = new Phaser.Geom.Rectangle(50, 50, 100, 80);

gfx.fillCircleShape(circle);
gfx.strokeCircleShape(circle);
gfx.fillRectShape(rect);
gfx.strokeRectShape(rect);
gfx.fillTriangleShape(triangle);
gfx.strokeTriangleShape(triangle);
gfx.strokeLineShape(line);
gfx.fillEllipseShape(ellipse, smoothness);
gfx.strokeEllipseShape(ellipse, smoothness);
Graphics提供便捷方法,可直接接收Phaser.Geom对象:
js
const circle = new Phaser.Geom.Circle(200, 200, 50);
const rect = new Phaser.Geom.Rectangle(50, 50, 100, 80);

gfx.fillCircleShape(circle);
gfx.strokeCircleShape(circle);
gfx.fillRectShape(rect);
gfx.strokeRectShape(rect);
gfx.fillTriangleShape(triangle);
gfx.strokeTriangleShape(triangle);
gfx.strokeLineShape(line);
gfx.fillEllipseShape(ellipse, smoothness);
gfx.strokeEllipseShape(ellipse, smoothness);

Canvas Transforms (Graphics)

画布变换(Graphics)

js
const gfx = this.add.graphics();

gfx.save();
gfx.translateCanvas(100, 100);
gfx.rotateCanvas(0.5);           // radians
gfx.scaleCanvas(2, 2);
gfx.fillStyle(0xff0000);
gfx.fillRect(0, 0, 50, 50);     // draws at translated/rotated/scaled position
gfx.restore();
js
const gfx = this.add.graphics();

gfx.save();
gfx.translateCanvas(100, 100);
gfx.rotateCanvas(0.5);           // 弧度
gfx.scaleCanvas(2, 2);
gfx.fillStyle(0xff0000);
gfx.fillRect(0, 0, 50, 50);     // 在经过平移/旋转/缩放的位置绘制
gfx.restore();

Generating Textures from Graphics

从Graphics生成纹理

js
const gfx = this.add.graphics();
gfx.fillStyle(0xff0000);
gfx.fillCircle(32, 32, 32);
gfx.generateTexture('redCircle', 64, 64);
gfx.destroy();

// Now use as a regular texture
this.add.image(400, 300, 'redCircle');
Note:
fillGradientStyle
will NOT appear in generated textures (Canvas API limitation).
js
const gfx = this.add.graphics();
gfx.fillStyle(0xff0000);
gfx.fillCircle(32, 32, 32);
gfx.generateTexture('redCircle', 64, 64);
gfx.destroy();

// 现在将其用作常规纹理
this.add.image(400, 300, 'redCircle');
注意:
fillGradientStyle
不会出现在生成的纹理中(Canvas API限制)。

Shape Objects — Fill and Stroke

Shape对象 — 填充与描边

js
// Shapes set fill via constructor or setFillStyle
const rect = this.add.rectangle(200, 150, 100, 80, 0xff0000, 1);

// Change fill later
rect.setFillStyle(0x00ff00, 0.8);

// Add stroke (not set by default)
rect.setStrokeStyle(3, 0xffffff, 1);  // (lineWidth, color, alpha)

// Remove fill or stroke
rect.setFillStyle();    // no args = isFilled becomes false
rect.setStrokeStyle();  // no args = isStroked becomes false

// Direct property access
rect.fillColor = 0x0000ff;
rect.fillAlpha = 0.5;
rect.strokeColor = 0xffffff;
rect.strokeAlpha = 1;
rect.lineWidth = 2;
rect.isFilled = true;
rect.isStroked = true;
rect.closePath = true;   // close stroke path (default true)

js
// 形状可通过构造函数或setFillStyle设置填充
const rect = this.add.rectangle(200, 150, 100, 80, 0xff0000, 1);

// 后续修改填充
rect.setFillStyle(0x00ff00, 0.8);

// 添加描边(默认未设置)
rect.setStrokeStyle(3, 0xffffff, 1);  // (线条宽度, 颜色, 透明度)

// 移除填充或描边
rect.setFillStyle();    // 无参数 = isFilled变为false
rect.setStrokeStyle();  // 无参数 = isStroked变为false

// 直接访问属性
rect.fillColor = 0x0000ff;
rect.fillAlpha = 0.5;
rect.strokeColor = 0xffffff;
rect.strokeAlpha = 1;
rect.lineWidth = 2;
rect.isFilled = true;
rect.isStroked = true;
rect.closePath = true;   // 自动闭合描边路径(默认true)

All Shape Types

所有Shape类型

Factory MethodClassParameters (after x, y)FillStrokeNotes
this.add.arc(x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha)
Arcradius=128, startAngle=0, endAngle=360 (degrees), anticlockwise=falseYesYesAngles in degrees. Full circle by default.
this.add.circle(x, y, radius, fillColor, fillAlpha)
Arcradius=128YesYesAlias for Arc with 0-360 angles.
this.add.curve(x, y, curve, fillColor, fillAlpha)
CurvePhaser.Curves.Curve objectYesYesHas
smoothness
property /
setSmoothness()
.
this.add.ellipse(x, y, width, height, fillColor, fillAlpha)
Ellipsewidth=128, height=128YesYesEqual w/h renders as circle. Has
smoothness
.
this.add.grid(x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha)
Gridwidth=128, height=128, cellWidth=32, cellHeight=32YesNoHas
altFillColor
/
altFillAlpha
for checkerboard. Outline via outlineFillColor.
this.add.isobox(x, y, size, height, fillTop, fillLeft, fillRight)
IsoBoxsize=48, height=32, fillTop=0xeeeeee, fillLeft=0x999999, fillRight=0xccccccYesNoIsometric box.
showTop
,
showLeft
,
showRight
,
projection
.
this.add.isotriangle(x, y, size, height, reversed, fillTop, fillLeft, fillRight)
IsoTrianglesize=48, height=32, reversed=falseYesNoIsometric pyramid.
showTop
,
showLeft
,
showRight
,
projection
,
reversed
.
this.add.line(x, y, x1, y1, x2, y2, strokeColor, strokeAlpha)
Linex1=0, y1=0, x2=128, y2=0NoYesStroke only. Constructor takes stroke color (not fill).
this.add.polygon(x, y, points, fillColor, fillAlpha)
Polygonpoints (various formats)YesYesPoints: array of Vec2,
[x,y,...]
pairs, or
[[x,y],...]
.
this.add.rectangle(x, y, width, height, fillColor, fillAlpha)
Rectanglewidth=128, height=128YesYesChange size via
width
/
height
properties.
this.add.star(x, y, points, innerRadius, outerRadius, fillColor, fillAlpha)
Starpoints=5, innerRadius=32, outerRadius=64YesYes4 points = diamond. More points = spikier.
this.add.triangle(x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha)
Trianglex1=0,y1=128, x2=64,y2=0, x3=128,y3=128YesYesAlways closed. Use Polygon for open shapes.

工厂方法参数(x, y之后)填充描边说明
this.add.arc(x, y, radius, startAngle, endAngle, anticlockwise, fillColor, fillAlpha)
Arcradius=128, startAngle=0, endAngle=360(度), anticlockwise=false角度为度。默认绘制完整圆形。
this.add.circle(x, y, radius, fillColor, fillAlpha)
Arcradius=128角度为0-360的Arc别名。
this.add.curve(x, y, curve, fillColor, fillAlpha)
CurvePhaser.Curves.Curve对象拥有
smoothness
属性 /
setSmoothness()
方法。
this.add.ellipse(x, y, width, height, fillColor, fillAlpha)
Ellipsewidth=128, height=128宽高相等时渲染为圆形。拥有
smoothness
属性。
this.add.grid(x, y, width, height, cellWidth, cellHeight, fillColor, fillAlpha, outlineFillColor, outlineFillAlpha)
Gridwidth=128, height=128, cellWidth=32, cellHeight=32拥有
altFillColor
/
altFillAlpha
实现棋盘格效果。通过outlineFillColor设置轮廓。
this.add.isobox(x, y, size, height, fillTop, fillLeft, fillRight)
IsoBoxsize=48, height=32, fillTop=0xeeeeee, fillLeft=0x999999, fillRight=0xcccccc等距立方体。拥有
showTop
showLeft
showRight
projection
属性。
this.add.isotriangle(x, y, size, height, reversed, fillTop, fillLeft, fillRight)
IsoTrianglesize=48, height=32, reversed=false等距金字塔。拥有
showTop
showLeft
showRight
projection
reversed
属性。
this.add.line(x, y, x1, y1, x2, y2, strokeColor, strokeAlpha)
Linex1=0, y1=0, x2=128, y2=0仅支持描边。构造函数接收描边颜色(而非填充颜色)。
this.add.polygon(x, y, points, fillColor, fillAlpha)
Polygonpoints(多种格式)Points格式:Vec2数组、
[x,y,...]
对、或
[[x,y],...]
this.add.rectangle(x, y, width, height, fillColor, fillAlpha)
Rectanglewidth=128, height=128通过
width
/
height
属性修改尺寸。
this.add.star(x, y, points, innerRadius, outerRadius, fillColor, fillAlpha)
Starpoints=5, innerRadius=32, outerRadius=644个点为菱形。点数越多越尖锐。
this.add.triangle(x, y, x1, y1, x2, y2, x3, y3, fillColor, fillAlpha)
Trianglex1=0,y1=128, x2=64,y2=0, x3=128,y3=128始终闭合。使用Polygon创建开放形状。

API Quick Reference — Graphics Methods

API快速参考 — Graphics方法

Style Methods

样式方法

MethodSignatureNotes
fillStyle
(color, alpha=1)
Set fill for subsequent fill calls
lineStyle
(lineWidth, color, alpha=1)
Set stroke for subsequent stroke calls
fillGradientStyle
(tl, tr, bl, br, aTL=1, aTR, aBL, aBR)
WebGL only. 4 corner colors.
lineGradientStyle
(lineWidth, tl, tr, bl, br, alpha=1)
WebGL only.
setDefaultStyles
(options)
Set via
{ lineStyle: {width,color,alpha}, fillStyle: {color,alpha} }
方法签名说明
fillStyle
(color, alpha=1)
为后续填充操作设置样式
lineStyle
(lineWidth, color, alpha=1)
为后续描边操作设置样式
fillGradientStyle
(tl, tr, bl, br, aTL=1, aTR, aBL, aBR)
仅WebGL支持。四个角的颜色。
lineGradientStyle
(lineWidth, tl, tr, bl, br, alpha=1)
仅WebGL支持。
setDefaultStyles
(options)
通过
{ lineStyle: {width,color,alpha}, fillStyle: {color,alpha} }
设置默认样式

Path Methods

路径方法

MethodSignatureNotes
beginPath
()
Start a new path
moveTo
(x, y)
Move draw position
lineTo
(x, y)
Line to position
arc
(x, y, radius, startAngle, endAngle, anticlockwise=false, overshoot=0)
Angles in radians
closePath
()
Close current path
fillPath
/
fill
()
Fill the current path
strokePath
/
stroke
()
Stroke the current path
slice
(x, y, radius, startAngle, endAngle, anticlockwise=false, overshoot=0)
Pie slice. Auto begins/closes path. Angles in radians.
方法签名说明
beginPath
()
开始新路径
moveTo
(x, y)
移动绘制位置
lineTo
(x, y)
绘制线条到目标位置
arc
(x, y, radius, startAngle, endAngle, anticlockwise=false, overshoot=0)
角度为弧度
closePath
()
闭合当前路径
fillPath
/
fill
()
填充当前路径
strokePath
/
stroke
()
描边当前路径
slice
(x, y, radius, startAngle, endAngle, anticlockwise=false, overshoot=0)
饼图切片。自动开始/闭合路径。角度为弧度。

Shape Drawing Methods

形状绘制方法

MethodSignature
fillRect
(x, y, width, height)
strokeRect
(x, y, width, height)
fillRoundedRect
(x, y, width, height, radius=20)
strokeRoundedRect
(x, y, width, height, radius=20)
fillCircle
(x, y, radius)
strokeCircle
(x, y, radius)
fillEllipse
(x, y, width, height, smoothness=32)
strokeEllipse
(x, y, width, height, smoothness=32)
fillTriangle
(x0, y0, x1, y1, x2, y2)
strokeTriangle
(x0, y0, x1, y1, x2, y2)
fillPoint
(x, y, size=1)
lineBetween
(x1, y1, x2, y2)
strokePoints
(points, closeShape=false, closePath=false, endIndex)
fillPoints
(points, closeShape=false, closePath=false, endIndex)
方法签名
fillRect
(x, y, width, height)
strokeRect
(x, y, width, height)
fillRoundedRect
(x, y, width, height, radius=20)
strokeRoundedRect
(x, y, width, height, radius=20)
fillCircle
(x, y, radius)
strokeCircle
(x, y, radius)
fillEllipse
(x, y, width, height, smoothness=32)
strokeEllipse
(x, y, width, height, smoothness=32)
fillTriangle
(x0, y0, x1, y1, x2, y2)
strokeTriangle
(x0, y0, x1, y1, x2, y2)
fillPoint
(x, y, size=1)
lineBetween
(x1, y1, x2, y2)
strokePoints
(points, closeShape=false, closePath=false, endIndex)
fillPoints
(points, closeShape=false, closePath=false, endIndex)

Geom Shape Methods

几何形状方法

MethodSignature
fillRectShape
(rect)
strokeRectShape
(rect)
fillCircleShape
(circle)
strokeCircleShape
(circle)
fillTriangleShape
(triangle)
strokeTriangleShape
(triangle)
strokeLineShape
(line)
fillEllipseShape
(ellipse, smoothness=32)
strokeEllipseShape
(ellipse, smoothness=32)
方法签名
fillRectShape
(rect)
strokeRectShape
(rect)
fillCircleShape
(circle)
strokeCircleShape
(circle)
fillTriangleShape
(triangle)
strokeTriangleShape
(triangle)
strokeLineShape
(line)
fillEllipseShape
(ellipse, smoothness=32)
strokeEllipseShape
(ellipse, smoothness=32)

Transform and State Methods

变换与状态方法

MethodSignatureNotes
translateCanvas
(x, y)
Translate subsequent draws
scaleCanvas
(x, y)
Scale subsequent draws
rotateCanvas
(radians)
Rotate subsequent draws
save
()
Push state to stack
restore
()
Pop state from stack
clear
()
Clear command buffer, reset to default styles
generateTexture
(key, width, height)
Bake to a Texture (Canvas API)
方法签名说明
translateCanvas
(x, y)
平移后续绘制内容
scaleCanvas
(x, y)
缩放后续绘制内容
rotateCanvas
(radians)
旋转后续绘制内容
save
()
将状态推入栈中
restore
()
从栈中弹出状态
clear
()
清除命令缓冲区,重置为默认样式
generateTexture
(key, width, height)
将绘制内容烘焙为Texture(基于Canvas API)

Shape Base Class Methods

Shape基类方法

MethodSignatureNotes
setFillStyle
(color?, alpha=1)
No args = disable fill
setStrokeStyle
(lineWidth?, color?, alpha=1)
No args = disable stroke

方法签名说明
setFillStyle
(color?, alpha=1)
无参数则禁用填充
setStrokeStyle
(lineWidth?, color?, alpha=1)
无参数则禁用描边

Gotchas

注意事项

  1. Graphics arc() uses radians; Shape arc factory uses degrees. The Graphics
    arc
    method takes start/end angles in radians. The
    this.add.arc()
    factory takes them in degrees (0-360). Mixing these up is the most common bug.
  2. Set style BEFORE drawing.
    fillStyle
    and
    lineStyle
    must be called before the corresponding fill/stroke method. They are not retroactive.
  3. Graphics has no Origin or GetBounds. Unlike Shape objects, Graphics does not include the Origin or GetBounds components. Use
    setPosition(x, y)
    and
    displayOriginX
    /
    displayOriginY
    instead.
  4. Shape isFilled/isStroked defaults. Shapes created with a
    fillColor
    parameter have
    isFilled = true
    . But
    isStroked
    defaults to
    false
    — you must call
    setStrokeStyle()
    explicitly.
  5. Line shape is stroke-only. The Line shape does not support fill. Its constructor takes
    strokeColor
    /
    strokeAlpha
    (not fillColor).
  6. IsoBox/IsoTriangle are fill-only. These shapes cannot be stroked. Grid supports outline strokes via its constructor parameters (
    outlineFillColor
    ,
    outlineFillAlpha
    ).
  7. generateTexture uses Canvas API. Gradient fills (
    fillGradientStyle
    ) will not appear in textures generated with
    generateTexture
    . Only Canvas-compatible features are captured.
  8. Performance: Graphics is expensive. Each frame the command buffer is replayed and geometry is rebuilt (WebGL decomposes to polygons). For static shapes, call
    generateTexture
    and use the resulting texture as a Sprite. Group Graphics objects together to minimize batch breaks.
  9. pathDetailThreshold (v4 new). Graphics has a
    pathDetailThreshold
    property (default -1, uses config
    render.pathDetailThreshold
    ). Path segments below this pixel threshold are combined, improving WebGL performance on complex shapes. Evaluated in screen pixels, so detail emerges when zoomed in.
  10. Rounded rect radius can be an object or number. Pass
    { tl, tr, bl, br }
    for per-corner control. Negative values create concave corners. Default is 20 when omitted.
  11. Shape closePath property. The
    closePath
    property on Shape objects (default
    true
    ) controls whether the stroke path is automatically closed. Set to
    false
    for open stroked shapes.
  12. Shape objects do NOT support tint methods. Unlike Sprites and Images, Shape game objects do not have
    setTint()
    or
    tint
    properties. Use
    setFillStyle(color, alpha)
    and
    setStrokeStyle(lineWidth, color, alpha)
    instead.
  13. Polygon getBounds() incorrect with negative points. If any polygon points have negative coordinates,
    getBounds()
    returns wrong values. Use
    Phaser.Geom.Polygon.GetAABB(polygon.geom)
    instead and adjust the returned Rectangle position.

  1. Graphics的arc()使用弧度;Shape的arc工厂方法使用角度。 Graphics的
    arc
    方法接收起始/结束角度为弧度。
    this.add.arc()
    工厂方法接收角度为度(0-360)。混淆两者是最常见的错误。
  2. 先设置样式再绘制。
    fillStyle
    lineStyle
    必须在对应的填充/描边方法之前调用,不会追溯生效。
  3. Graphics无Origin或GetBounds。 与Shape对象不同,Graphics不包含Origin或GetBounds组件。请使用
    setPosition(x, y)
    displayOriginX
    /
    displayOriginY
    替代。
  4. Shape的isFilled/isStroked默认值。 通过
    fillColor
    参数创建的Shape,其
    isFilled = true
    。但
    isStroked
    默认值为
    false
    ——你必须显式调用
    setStrokeStyle()
  5. Line形状仅支持描边。 Line形状不支持填充。其构造函数接收
    strokeColor
    /
    strokeAlpha
    (而非fillColor)。
  6. IsoBox/IsoTriangle仅支持填充。 这些形状无法描边。Grid可通过构造函数参数(
    outlineFillColor
    outlineFillAlpha
    )设置轮廓描边。
  7. generateTexture使用Canvas API。 使用
    generateTexture
    生成的纹理中不会显示渐变填充(
    fillGradientStyle
    )。仅能捕获Canvas兼容的特性。
  8. 性能:Graphics成本高。 每帧都会重放命令缓冲区并重建几何图形(WebGL会分解为多边形)。对于静态形状,调用
    generateTexture
    并将生成的纹理用作Sprite。将Graphics对象分组以最小化批次中断。
  9. pathDetailThreshold(v4新增)。 Graphics拥有
    pathDetailThreshold
    属性(默认-1,使用配置项
    render.pathDetailThreshold
    )。低于此像素阈值的路径段会被合并,提升复杂形状的WebGL性能。以屏幕像素为单位评估,缩放时会显示细节。
  10. 圆角矩形半径可为对象或数字。 传入
    { tl, tr, bl, br }
    可单独控制每个角的半径。负值会创建凹角。省略时默认值为20。
  11. Shape的closePath属性。 Shape对象的
    closePath
    属性(默认
    true
    )控制是否自动闭合描边路径。设置为
    false
    可创建开放描边形状。
  12. Shape对象不支持着色方法。 与Sprite和Image不同,Shape游戏对象没有
    setTint()
    tint
    属性。请使用
    setFillStyle(color, alpha)
    setStrokeStyle(lineWidth, color, alpha)
    替代。
  13. Polygon的getBounds()在点为负值时不准确。 如果多边形的任何点坐标为负值,
    getBounds()
    会返回错误值。请使用
    Phaser.Geom.Polygon.GetAABB(polygon.geom)
    替代,并调整返回的Rectangle位置。

Shape-Specific Methods

特定Shape方法

Star

Star

js
const star = this.add.star(400, 300, 5, 32, 64, 0xffff00);

star.setPoints(8);          // change number of points
star.setInnerRadius(20);    // change inner radius
star.setOuterRadius(80);    // change outer radius
js
const star = this.add.star(400, 300, 5, 32, 64, 0xffff00);

star.setPoints(8);          // 修改点数
star.setInnerRadius(20);    // 修改内半径
star.setOuterRadius(80);    // 修改外半径

Line (Tapering)

Line(渐变宽度)

js
const line = this.add.line(400, 300, 0, 0, 200, 100, 0xffffff);

// setLineWidth(startWidth, endWidth) — endWidth is WebGL only (tapering effect)
line.setLineWidth(4, 1);   // tapers from 4px to 1px (Canvas uses startWidth only)
js
const line = this.add.line(400, 300, 0, 0, 200, 100, 0xffffff);

// setLineWidth(startWidth, endWidth) — endWidth仅WebGL支持(渐变宽度效果)
line.setLineWidth(4, 1);   // 从4px渐变到1px(Canvas仅使用startWidth)

Grid (Alternating Colors, Stroke, Padding)

Grid(交替颜色、描边、内边距)

js
const grid = this.add.grid(400, 300, 320, 240, 32, 32, 0x222222);

// Alternating cell color (checkerboard)
grid.setAltFillStyle(0x444444, 1);  // no args = disable alternating cells

// Grid uses setStrokeStyle for cell outlines (inherited from Shape)
grid.setStrokeStyle(1, 0x666666, 1);

// v4: control outside edge stroke
grid.strokeOutside = true;             // stroke the outer border
grid.strokeOutsideIncomplete = false;  // skip partial cells on right/bottom edges

// Cell padding (default 0.5) — gutter between cells is 2x this value
grid.cellPadding = 1;
js
const grid = this.add.grid(400, 300, 320, 240, 32, 32, 0x222222);

// 交替单元格颜色(棋盘格)
grid.setAltFillStyle(0x444444, 1);  // 无参数则禁用交替单元格

// Grid使用setStrokeStyle设置单元格轮廓(继承自Shape)
grid.setStrokeStyle(1, 0x666666, 1);

// v4:控制外边缘描边
grid.strokeOutside = true;             // 描外边框
grid.strokeOutsideIncomplete = false;  // 跳过右侧/底部的不完整单元格

// 单元格内边距(默认0.5)— 单元格间距为此值的2倍
grid.cellPadding = 1;

IsoBox / IsoTriangle

IsoBox / IsoTriangle

js
const box = this.add.isobox(200, 200, 48, 32, 0xeeeeee, 0x999999, 0xcccccc);

box.setFaces(true, true, false);  // showTop, showLeft, showRight
box.setProjection(4);             // isometric projection value

const tri = this.add.isotriangle(400, 200, 48, 32, false, 0xeeeeee, 0x999999, 0xcccccc);

tri.setReversed(true);            // flip upside down
tri.setFaces(true, true, true);
tri.setProjection(4);

js
const box = this.add.isobox(200, 200, 48, 32, 0xeeeeee, 0x999999, 0xcccccc);

box.setFaces(true, true, false);  // showTop, showLeft, showRight
box.setProjection(4);             // 等距投影值

const tri = this.add.isotriangle(400, 200, 48, 32, false, 0xeeeeee, 0x999999, 0xcccccc);

tri.setReversed(true);            // 翻转
ntri.setFaces(true, true, true);
tri.setProjection(4);

Source File Map

源文件映射

FilePurpose
src/gameobjects/graphics/Graphics.js
Graphics class — all drawing methods
src/gameobjects/graphics/GraphicsFactory.js
this.add.graphics()
factory
src/gameobjects/graphics/Commands.js
Internal command constants for the command buffer
src/gameobjects/graphics/GraphicsRender.js
Render dispatch
src/gameobjects/shape/Shape.js
Base Shape class (fill/stroke/path data, setFillStyle, setStrokeStyle)
src/gameobjects/shape/arc/Arc.js
Arc shape (also used for circle)
src/gameobjects/shape/arc/ArcFactory.js
this.add.arc()
and
this.add.circle()
factories
src/gameobjects/shape/curve/Curve.js
Curve shape
src/gameobjects/shape/curve/CurveFactory.js
this.add.curve()
factory
src/gameobjects/shape/ellipse/Ellipse.js
Ellipse shape
src/gameobjects/shape/ellipse/EllipseFactory.js
this.add.ellipse()
factory
src/gameobjects/shape/grid/Grid.js
Grid shape
src/gameobjects/shape/grid/GridFactory.js
this.add.grid()
factory
src/gameobjects/shape/isobox/IsoBox.js
IsoBox shape
src/gameobjects/shape/isobox/IsoBoxFactory.js
this.add.isobox()
factory
src/gameobjects/shape/isotriangle/IsoTriangle.js
IsoTriangle shape
src/gameobjects/shape/isotriangle/IsoTriangleFactory.js
this.add.isotriangle()
factory
src/gameobjects/shape/line/Line.js
Line shape
src/gameobjects/shape/line/LineFactory.js
this.add.line()
factory
src/gameobjects/shape/polygon/Polygon.js
Polygon shape
src/gameobjects/shape/polygon/PolygonFactory.js
this.add.polygon()
factory
src/gameobjects/shape/rectangle/Rectangle.js
Rectangle shape
src/gameobjects/shape/rectangle/RectangleFactory.js
this.add.rectangle()
factory
src/gameobjects/shape/star/Star.js
Star shape
src/gameobjects/shape/star/StarFactory.js
this.add.star()
factory
src/gameobjects/shape/triangle/Triangle.js
Triangle shape
src/gameobjects/shape/triangle/TriangleFactory.js
this.add.triangle()
factory
文件用途
src/gameobjects/graphics/Graphics.js
Graphics类 — 所有绘制方法
src/gameobjects/graphics/GraphicsFactory.js
this.add.graphics()
工厂方法
src/gameobjects/graphics/Commands.js
命令缓冲区的内部命令常量
src/gameobjects/graphics/GraphicsRender.js
渲染调度
src/gameobjects/shape/Shape.js
基础Shape类(填充/描边/路径数据、setFillStyle、setStrokeStyle)
src/gameobjects/shape/arc/Arc.js
Arc形状(也用于圆形)
src/gameobjects/shape/arc/ArcFactory.js
this.add.arc()
this.add.circle()
工厂方法
src/gameobjects/shape/curve/Curve.js
Curve形状
src/gameobjects/shape/curve/CurveFactory.js
this.add.curve()
工厂方法
src/gameobjects/shape/ellipse/Ellipse.js
Ellipse形状
src/gameobjects/shape/ellipse/EllipseFactory.js
this.add.ellipse()
工厂方法
src/gameobjects/shape/grid/Grid.js
Grid形状
src/gameobjects/shape/grid/GridFactory.js
this.add.grid()
工厂方法
src/gameobjects/shape/isobox/IsoBox.js
IsoBox形状
src/gameobjects/shape/isobox/IsoBoxFactory.js
this.add.isobox()
工厂方法
src/gameobjects/shape/isotriangle/IsoTriangle.js
IsoTriangle形状
src/gameobjects/shape/isotriangle/IsoTriangleFactory.js
this.add.isotriangle()
工厂方法
src/gameobjects/shape/line/Line.js
Line形状
src/gameobjects/shape/line/LineFactory.js
this.add.line()
工厂方法
src/gameobjects/shape/polygon/Polygon.js
Polygon形状
src/gameobjects/shape/polygon/PolygonFactory.js
this.add.polygon()
工厂方法
src/gameobjects/shape/rectangle/Rectangle.js
Rectangle形状
src/gameobjects/shape/rectangle/RectangleFactory.js
this.add.rectangle()
工厂方法
src/gameobjects/shape/star/Star.js
Star形状
src/gameobjects/shape/star/StarFactory.js
this.add.star()
工厂方法
src/gameobjects/shape/triangle/Triangle.js
Triangle形状
src/gameobjects/shape/triangle/TriangleFactory.js
this.add.triangle()
工厂方法