360 Secure SkillHub
360 安全技能中心

graphics-and-shapes

该 Skill 是一份 Phaser 4.3 图形绘制参考,讲解 Graphics 与 Shape 两类对象的填充、描边、路径、圆角、渐变、线条连接、SDF 渲染、cleanAlpha 和纹理烘焙,并给出 HUD、血条、UI 面板与调试覆盖层等代码示例。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:17

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/graphics-and-shapes
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
graphics-and-shapes
description
Draw vector shapes in Phaser 4 with the Graphics object (fillRect, fillCircle, fillRoundedRect, lineStyle, strokePath, arc, slice, generateTexture) and the Shape objects (this.add.rectangle, circle, arc, ellipse, line, polygon, star, triangle, grid, isobox, isotriangle, curve; setFillStyle, setStrokeStyle, setRounded). Covers the 4.3 SDF renderer (render.sdfShapes, hardEdges), line joins (miterLimit, lineJoin), gradient fills and strokes (fillLinearGradient, fillRadialGradient, setFillLinearGradient), cleanAlpha, and baking to a texture. Use when drawing a health bar, HUD, UI panel, button, debug overlay, outline, pie or radar chart, or any procedural shape. Corrects old habits: Graphics arcs are radians but Shape arcs are degrees, a Shape with no color is invisible, gradients are no longer WebGL-only 4-corner tints, baking is never automatic. Triggers on: Graphics, Shape, draw shape, fillRect, lineStyle, gradient, rounded rectangle, line join, miter.
metadata
{"phaser-version":"4.3.0"}

Graphics and Shapes

Drawing vector primitives with the Graphics Game Object and the Shape Game Objects, and how Phaser 4.3 renders them.

Source: src/gameobjects/graphics/Graphics.js, src/gameobjects/shape/Shape.js, src/gameobjects/shape/<kind>/. Related: game-object-components, masks-and-stencils, lighting, render-textures, sprites-and-images.

Quick start

// Graphics: one object, many shapes, drawn from a command list
const g = this.add.graphics();
g.fillStyle(0x00aa00, 1);
g.fillRoundedRect(50, 50, 200, 100, 16);
g.lineStyle(4, 0xffffff, 1);
g.strokeCircle(400, 100, 60);

// Shapes: one Game Object per shape, with origin, bounds, input and tweens
const box = this.add.rectangle(this.scale.width / 2, 300, 200, 100, 0x3a86ff)
    .setStrokeStyle(4, 0xffffff);
const star = this.add.star(700, 300, 5, 30, 60, 0xffcc00);

Graphics or Shape?

  • Graphics: many shapes in one object, paths, anything redrawn every frame (clear() then draw). No Origin, no GetBounds, no size. Everything is drawn relative to the Graphics position, and it rotates and scales around its own (0, 0).
  • Shape: one shape per object. Has Origin (0.5), GetBounds, size and a default hit area, so it suits UI, input, tweens and physics bodies. No Tint: use setFillStyle / setStrokeStyle.
  • Both batch together in WebGL, and both have Lighting, cleanAlpha, hardEdges, miter limits and line joins.

Graphics

// Options: x, y, fillStyle, lineStyle, and (4.3) miterLimit, lineJoin, hardEdges, cleanAlpha
const g = this.add.graphics({ x: 100, y: 100, lineStyle: { width: 2, color: 0xffffff }, fillStyle: { color: 0xff0000 } });

g.fillRect(0, 0, 100, 50);
g.strokeRect(0, 0, 100, 50);
g.fillRoundedRect(0, 80, 200, 60, { tl: 20, tr: 20, bl: 0, br: 0 }); // radius number or per corner (default 20)
g.fillEllipse(300, 40, 120, 60);
g.fillTriangle(0, 200, 50, 150, 100, 200);
g.lineBetween(0, 250, 200, 250);
g.fillPoint(250, 250, 4);

// Paths. Angles are RADIANS on Graphics.
g.beginPath();
g.moveTo(300, 150);
g.lineTo(400, 200);
g.lineTo(300, 250);
g.closePath();
g.strokePath();             // or fillPath(); fill() and stroke() are aliases

g.slice(500, 200, 50, Phaser.Math.DegToRad(30), Phaser.Math.DegToRad(330)); // pie: begins and closes its own path
g.fillPath();

const points = [ { x: 600, y: 150 }, { x: 700, y: 180 }, { x: 650, y: 260 } ];
g.strokePoints(points, true);   // second argument closes the shape
g.clear();                      // empties the command list; re-applies option styles, if any
  • Styles are commands. Set fillStyle / lineStyle before the draw call they apply to. With no style given in the options, the default fill and line have an alpha of 0, so nothing shows.
  • Geom helpers take Geom objects: fillRectShape, strokeRectShape, fillCircleShape, strokeCircleShape, fillTriangleShape, strokeTriangleShape, strokeLineShape, fillEllipseShape, strokeEllipseShape, fillPointShape.
  • translateCanvas, scaleCanvas, rotateCanvas, save and restore transform the commands after them.
  • this.make.graphics(config) does not add the object to the display list unless config.add is true. Use it for mask sources and for baking.
  • Input: a Graphics has no size, so give it a hit area: g.setInteractive(new Phaser.Geom.Rectangle(0, 0, 100, 50), Phaser.Geom.Rectangle.Contains).

How 4.3 renders them (WebGL)

The game config render.sdfShapes is true by default. Circles, ellipses, arcs, slices, rounded rectangles, stroked rectangles, single lines and every line of a stroked path are each one quad, with the shape worked out in the fragment shader (a signed distance field). They are truly round at any zoom, antialiased in Render Textures and Filters too, and a see-through stroke no longer darkens at its joins.

  • Still drawn as triangles, in the same batch: plain filled rectangles, polygons, stars, triangles, grids, iso shapes, arbitrary filled paths, and arcs with overshoot.
  • A Graphics keeps the triangles of its filled paths in fillPathCache and only cuts a path up again when its points change. There is nothing to clear or manage.
  • render.pathDetailThreshold (default 1 pixel) and Graphics.pathDetailThreshold (default -1, use the config) drop path points that are closer than that.
  • Turn it off for the whole game with render: { sdfShapes: false }. Draw one object with triangles: obj.setRenderNodeRole('Submitter', 'BatchHandlerTriFlat'). Reset with obj.setRenderNodeRole('Submitter', null).
  • antialiasGL: false or pixelArt: true makes SDF edges hard.

Hard edges

const maskShape = this.make.graphics({ hardEdges: true });  // or shape.setHardEdges()
maskShape.fillStyle(0xffffff);
maskShape.fillCircle(this.scale.width / 2, this.scale.height / 2, 120);

hardEdges makes every SDF pixel fully in or out, still perfectly round. Use it for a Mask filter source that needs a crisp edge, or pixel art. Shapes drawn by a Stencil are always cut hard, so they don't need it. It has no effect on triangles or in Canvas. Masking itself is covered in masks-and-stencils.

Line joins and miter limit (4.3)

Stroked paths now have pointed (miter) joins by default, like the Canvas API. A join longer than the miter limit (a multiple of the line width, default 10) is cut off (bevel).

const g = this.add.graphics({ lineJoin: 'round' });   // 'miter' (default), 'bevel' or 'round'
g.defaultMiterLimit = 1;                               // 1 = cut every join off, as before 4.3
g.lineStyle(12, 0xffcc00);
g.lineJoin('bevel');           // command: applies to paths stroked after it
g.strokePoints([ { x: 50, y: 50 }, { x: 150, y: 80 }, { x: 60, y: 140 } ], true);
g.lineJoin();                  // back to defaultLineJoin
g.miterLimit(2);               // command; miterLimit() with no value returns to defaultMiterLimit

this.add.star(300, 300, 5, 30, 70).setStrokeStyle(8, 0xffffff).setLineJoin('round').setMiterLimit(4);
  • Joins apply to strokePath, strokePoints, strokeTriangle, a closed slice / arc, and the strokes of Curve, Polygon, Star, Triangle and a closed Arc.
  • Rectangles always have square corners: use strokeRoundedRect or setRounded. Open path ends are always square. There are no round caps.
  • defaultMiterLimit and defaultLineJoin are read at render time, so changing them changes paths already drawn.
  • In WebGL they do nothing when sdfShapes is off, or for a path whose points have different widths (such as a tapered Line). Canvas always follows them.

Gradients (4.3)

Any number of stops, in both renderers, and baked by generateTexture. A stop is a color, or { color, alpha, offset } (offset 0 to 1). Two stops at the same offset make a hard band.

const g = this.add.graphics();
g.fillLinearGradient(0, 0, 0, 300, [ 0x87ceeb, { color: 0xffffff, offset: 0.6 }, 0x2e8b57 ]);
g.fillRect(0, 0, 400, 300);

g.fillRadialGradient(560, 120, 0, 100, [ 0xffffff, 0xffcc00, { color: 0xff6600, alpha: 0 } ]);
g.fillCircle(560, 120, 100);

g.lineLinearGradient(6, 0, 0, 800, 0, [ 0xff006e, 0xffbe0b, 0x3a86ff ]); // line width first
g.strokeRoundedRect(450, 250, 300, 120, 24);

// Shapes: coordinates are the Shape's own, (0, 0) = its top-left, whatever its origin
this.add.rectangle(200, 500, 200, 100).setFillLinearGradient(0, 0, 200, 0, [ 0xff006e, 0x3a86ff ]);
this.add.circle(500, 500, 55).setFillRadialGradient(36, 32, 4, 84, [ 0xffffff, 0xe63946, 0x5c0a14 ]);
this.add.star(700, 500, 5, 30, 60).setStrokeRadialGradient(6, 60, 60, 0, 60, [ 0xffffff, 0xff7b00 ]);
  • Graphics gradients are in the Graphics' coordinates and lie across the whole object, so several shapes share one. Call it again per shape for separate gradients. fillStyle / lineStyle end them.
  • Shape: setFillLinearGradient(x0, y0, x1, y1, stops), setFillRadialGradient(x, y, r0, r1, stops), setStrokeLinearGradient(lineWidth, ...), setStrokeRadialGradient(lineWidth, ...), stored in fillGradient / strokeGradient. setFillStyle / setStrokeStyle remove them. Line, Triangle, Polygon and Curve use the coordinates their points were given in. IsoBox and IsoTriangle have no gradients.
  • While a gradient is set, fillColor / fillAlpha (or the stroke ones) are ignored; each stop has its own alpha.
  • The old 4-corner fillGradientStyle(tl, tr, bl, br, alphaTL, ...) and lineGradientStyle(width, tl, tr, bl, br, alpha) still exist. They are WebGL only (Canvas ignores them and they don't bake). With sdfShapes on they blend across each whole shape's bounds; with it off, across each triangle. Prefer the new methods.

Clean alpha (4.3, WebGL only)

this.add.rectangle(300, 200, 200, 100, 0x3a86ff)
    .setStrokeStyle(16, 0xffbe0b)
    .setAlpha(0.5)
    .setCleanAlpha();                            // Graphics: this.add.graphics({ cleanAlpha: true })

Normally a faded object's overlapping parts show through each other (a stroke over its fill, overlapping Graphics shapes). With cleanAlpha the object is drawn at alpha 1 to a Camera-sized texture and that texture is faded once. It costs a framebuffer pass and a draw call per faded object, so only use it where it's needed. It does nothing at alpha 1, in Canvas, or while renderFilters is false. It calls enableFilters() for you.

Baking to a texture

Baking is never automatic. For a complex static drawing, bake it once by hand:

const g = this.make.graphics();
g.fillStyle(0xffffff);
g.fillCircle(16, 16, 16);
g.generateTexture('dot', 32, 32);   // drawn by the Canvas renderer into a new canvas texture
g.destroy();
this.add.image(100, 100, 'dot');
  • generateTexture(key, width, height) defaults to the game size. It draws in the Graphics' local coordinates. If key already exists as a canvas texture it draws onto it without clearing.
  • It uses the Canvas renderer, so the new gradients, miter limits and joins are included, but fillGradientStyle / lineGradientStyle are not.
  • To bake Shapes, Sprites or a mix, draw them to a DynamicTexture instead: see render-textures.

Shapes

Factory (after x, y) Defaults Notes
rectangle(w, h, fill, alpha) 128x128 setRounded(radius=16); resize with setSize(w, h)
circle(radius, fill, alpha) radius 128 An Arc from 0 to 360
arc(radius, startAngle, endAngle, anticlockwise, fill, alpha) 0 to 360 Angles in degrees
ellipse(w, h, fill, alpha) 128x128 setSmoothness, setSize
line(x1, y1, x2, y2, strokeColor, strokeAlpha) 0,0 to 128,0 Stroke only; setTo(x1, y1, x2, y2); width from setLineWidth
polygon(points, fill, alpha) Points: [x,y,...], [{x,y}], [[x,y]] or 'x y x y'; setTo(points), smooth(n)
triangle(x1, y1, x2, y2, x3, y3, fill, alpha) setTo(...)
star(points, innerRadius, outerRadius, fill, alpha) 5, 32, 64 setPoints, setInnerRadius, setOuterRadius
grid(w, h, cellW, cellH, fill, alpha, strokeColor, strokeAlpha) 128x128, 32x32 setAltFillStyle(color, alpha), setCellPadding(n) (default 0.5), setStrokeOutside(bool, incomplete)
curve(curve, fill, alpha) A Phaser.Curves curve; setSmoothness(n)
isobox(size, height, fillTop, fillLeft, fillRight) 48, 32 Fill only. setFillStyle(top, left, right), setFaces, setProjection
isotriangle(size, height, reversed, fillTop, fillLeft, fillRight) 48, 32 As IsoBox, plus setReversed
const r = this.add.rectangle(200, 150, 100, 80);   // no color given: isFilled is false, it is invisible
r.setFillStyle(0xff0000, 0.8);                      // setFillStyle() with no args turns the fill off
r.setStrokeStyle(3, 0xffffff);                      // isStroked defaults to false
r.setSize(160, 80);                                 // not r.width = 160, which doesn't rebuild the shape

const arc = this.add.arc(500, 150, 60, 0, 270, false).setStrokeStyle(6, 0xffffff);
arc.setClosePath(false);                            // stroke the curve only, without lines to the center

const line = this.add.line(0, 0, 100, 100, 300, 150, 0xffffff).setOrigin(0); // origin 0: points are world coords here
line.setLineWidth(4);                               // not setStrokeStyle(4, ...): WebGL ignores that width

Recipes

// Health bar from two Shapes, fixed to the camera
const back = this.add.rectangle(20, 20, 204, 20, 0x000000).setOrigin(0).setScrollFactor(0).setStrokeStyle(2, 0xffffff);
const fill = this.add.rectangle(22, 22, 200, 16, 0x00ff00).setOrigin(0).setScrollFactor(0);

const setHealth = (hp, max) =>
{
    fill.scaleX = Phaser.Math.Clamp(hp / max, 0, 1);
    fill.setFillStyle(hp / max < 0.3 ? 0xff0000 : 0x00ff00);
};

// UI panel: a rounded, outlined rectangle (use a NineSlice for a textured panel)
const panel = this.add.rectangle(this.scale.width / 2, this.scale.height / 2, 400, 240, 0x1d3557, 0.9)
    .setRounded(16)
    .setStrokeStyle(3, 0xffffff);

// Debug overlay: one Graphics, cleared and redrawn in update()
const debug = this.add.graphics();
debug.clear().lineStyle(1, 0x00ff00).strokeRectShape(panel.getBounds());

Gotchas

  1. Radians vs degrees. Graphics arc and slice take radians. The this.add.arc() Shape takes degrees.
  2. Invisible by default. A Shape made without a fill color, or a Graphics with no fillStyle / lineStyle, draws nothing.
  3. Polygon points are relative to the Shape's top-left. Give points starting near (0, 0). Points with negative values make getBounds() wrong; use Phaser.Geom.Polygon.GetAABB(polygon.geom).
  4. Line width on a Line Shape. Use setLineWidth(width), which both renderers read; setLineWidth(start, end) tapers in WebGL. setStrokeStyle(width, color) changes only the width Canvas uses, so in WebGL the line stays 1 pixel wide.
  5. Graphics rotates around its own (0, 0). Draw centered on (0, 0) and move the Graphics with setPosition to spin a shape in place.
  6. Redraw cost. A Graphics that is cleared and redrawn every frame rebuilds its command list. Fine for debug and a few dynamic shapes; for many static shapes draw once, or bake.
  7. No tint on Shapes or Graphics. Change colors with the style methods.
  8. Arc overshoot forces triangles. It was a workaround for seams in thick WebGL strokes and isn't needed with SDF.
  9. Grid lines. setStrokeStyle strokes the lines between cells. setStrokeOutside(true) adds the outer border.
  10. Lighting and masks. Both Graphics and Shapes support setLighting(true) (lighting) and can be Mask filter or Stencil sources (masks-and-stencils).