360 Secure SkillHub
360 安全技能中心

filters-and-postfx

面向 Phaser 4 的滤镜与后处理参考,说明 WebGL 滤镜列表、内部/外部 FilterList、内边距、相机与游戏对象用法,并给出辉光、模糊、泛光、擦除、颜色矩阵等效果的代码配方与常见注意事项。

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

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/filters-and-postfx
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
filters-and-postfx
description
Phaser 4 Filters, the WebGL post-processing effects for Game Objects and Cameras: enableFilters, filters.internal and filters.external, FilterList, Controllers, padding (setPaddingOverride), and the list of built-in filters, such as Blur, Glow, Shadow, ColorMatrix, Vignette, Pixelate, Bokeh, Barrel, Displacement, Wipe, Threshold, GradientMap, Blend, ParallelFilters and Mask, plus AddEffectBloom, AddEffectShine and CaptureFrame. Use when adding a glow, outline, blur, drop shadow, bloom, grayscale or sepia, pixelation, a screen wipe, or a blurred background behind a pause menu. Replaces v3 preFX, postFX and FX pipelines, which don't exist in v4. Triggers on: filter, effect, FX, preFX, postFX, post-processing, glow, blur, bloom, shadow, vignette, wipe, transition, grayscale.
metadata
{"phaser-version":"4.3.0"}

Filters and post-processing

Filters are Phaser 4's shader effects. Each one takes the image of a Game Object or Camera and draws a new one. They replace v3's preFX, postFX and post pipelines. This skill owns the list of filters.

Source: src/filters/, src/gameobjects/components/Filters.js, src/gameobjects/components/FilterList.js, src/actions/AddEffectBloom.js, src/actions/AddEffectShine.js. Related: masks-and-stencils, custom-rendering, cameras, lighting, phaser4-core.

Quick start

create ()
{
    const { width, height } = this.scale;
    const hero = this.add.sprite(width / 2, height / 2, 'hero');

    //  Filters are WebGL only. In Canvas, enableFilters() does nothing and hero.filters stays null.
    if (this.renderer.type === Phaser.WEBGL)
    {
        hero.enableFilters();

        //  A glow draws outside the sprite. setPaddingOverride(null) lets it pad the texture,
        //  or the glow is cut off at the sprite's edges.
        hero.filters.internal.addGlow(0xffff00, 4).setPaddingOverride(null);

        //  Cameras always have filters. No enableFilters() needed.
        this.cameras.main.filters.external.addVignette(0.5, 0.5, 0.6, 0.4);
    }
}
  • obj.filters is null until enableFilters() is called. enableFilters() returns early when there's no WebGL context, so obj.filters.internal throws in Canvas.
  • Since 4.3, Phaser.AUTO falls back to Canvas when the WebGL context can't be created, so a game set to AUTO can run without filters. Guard every filter call.
  • filters is { internal, external }: two FilterList objects. Each add* method returns the new Controller, which you change at any time.

Internal and external

A Camera with filters renders in five steps:

  1. Its objects render to a texture the size of the Camera.
  2. The internal filters run on that texture, in Camera (or object) space.
  3. The texture is drawn to a texture the size of the context, applying the Camera's own transform.
  4. The external filters run on that, in screen space.
  5. The result is drawn to the context.

A Game Object with filters uses the same steps, through its own filterCamera.

  • Internal filters work on the object as if it were unrotated and unscaled. A horizontal blur turns with the object. The texture is only as big as the object, so they're cheaper. Use them by default.
  • External filters work on the screen. A horizontal blur stays horizontal. The texture is as big as the context, usually the game canvas.
  • Each list runs in order. A filter gets the output of the one before.
  • v3's preFX maps to filters.internal, and postFX to filters.external.

Padding: why a glow gets cut off

An internal filter draws into a texture the size of the object. Blur, Glow, Shadow, Displacement and Bokeh/TiltShift draw past those edges.

  • Each Controller has a paddingOverride, and it defaults to a zero Rectangle. So automatic padding is off, and these filters are clipped at the object's bounds.
  • controller.setPaddingOverride(null) turns automatic padding on. The filter then works out how much room it needs.
  • setPaddingOverride(left, top, right, bottom) sets the edges by hand. To add 10 pixels all round, the left and top are negative: setPaddingOverride(-10, -10, 10, 10). setPaddingOverride(10, 10, 10, 10) moves the texture and adds nothing.
  • setPaddingOverride() with no arguments sets zero padding again.
  • A Camera's internal filters only see what's inside the Camera. For a full-screen Blur, enlarge the Camera with const cam = this.cameras.main.getPaddingWrapper(16), then use cam in place of the Camera. Only one wrapper per Camera at a time.
  • In a custom render node, read padding with getPaddingCeil() (4.1), not getPadding().

Objects which focus on the context

Filters focus their camera on the object, using its position, size and origin. Some objects have no usable size, so filtersFocusContext is turned on for them, and their internal filters render at the size of the Camera, like external filters:

  • Graphics, Layers, and Containers with no size (no setSize).
  • Shapes, always, so their stroke isn't cut off. Set shape.filtersFocusContext = false to focus on the Shape's own bounds.
  • Any object whose width or height is 0 when enableFilters() is called.

These were fixed in 4.3, so the following work as expected:

  • Such objects now follow their scroll factor. A HUD Container with setScrollFactor(0) and a filter stays put.
  • They're drawn in the right place on a Camera which isn't at the top left of the game, or is zoomed with an origin other than 0.5.
  • Containers with filters and a scroll factor can be nested, each with children which have filters of their own.

Layer filters have worked since 4.1, and a Layer is a true GameObject.

The Filters component

Every Game Object has the Filters component (WebGL only). See the matrix in game-object-components.

Member Default Use
enableFilters() Creates filterCamera and the lists. Returns this.
filters null { internal, external }, read only.
filterCamera null The Camera which renders the object for its filters.
renderFilters / setRenderFilters(bool) true false skips all filters, without removing them.
filtersAutoFocus / setFiltersAutoFocus(bool) true Refocus filterCamera on the object every frame.
filtersFocusContext / setFiltersFocusContext(bool) false Render internal filters at the size of the Camera.
filtersForceComposite / setFiltersForceComposite(bool) false Always draw through a framebuffer, even with no active filters.
maxFilterSize max texture size A Vector2 cap on the filter texture size.
willRenderFilters() true if any filter is active.
focusFiltersOverride(x, y, width, height) Place the filter camera by hand. Turns off filtersAutoFocus.
setFilterSize(width, height) The base texture size, when auto focus is off.

FilterList: add(controller, index), remove(controller, forceDestroy) (destroys it), clear(), getActive(), and list, the array of Controllers, which you can reorder.

Every Controller (Phaser.Filters.Controller): active / setActive(bool) to turn it off without removing it, setPaddingOverride(...), ignoreDestroy (keep it alive when its list is destroyed, to share it; you then destroy it yourself), and destroy().

The filters

All are in Phaser.Filters and are added through a FilterList. Defaults are shown.

Filter Add method Notes
Barrel addBarrel(amount = 1) Pinch or bulge. 1 is no change.
Blend addBlend(texture = '__WHITE', blendMode = NORMAL, amount = 1, color = [1, 1, 1, 1]) Blends a texture with any of the Canvas blend modes, in WebGL.
Blocky addBlocky({ size, offset }) Pixelation which keeps the original colors. Best for pixel art.
Blur addBlur(quality = 0, x = 2, y = 2, strength = 1, color = 0xffffff, steps = 4) quality 0, 1 or 2. Needs padding.
Bokeh addBokeh(radius = 0.5, amount = 1, contrast = 0.2) Depth of field blur. Needs padding.
TiltShift addTiltShift(radius, amount, contrast, blurX = 1, blurY = 1, strength) A Bokeh in tilt-shift mode: the miniature look.
ColorMatrix addColorMatrix() Color grading. Call presets on its colorMatrix property.
CombineColorMatrix addCombineColorMatrix(texture = '__WHITE') Mixes channels, such as alpha, from two images.
Displacement addDisplacement(texture = '__WHITE', x = 0.005, y = 0.005) Distorts by a displacement map. Small values. Needs padding.
Glow addGlow(color = 0xffffff, outerStrength = 4, innerStrength = 0, scale = 1, knockout = false, quality = 10, distance = 10) Outline or halo. quality and distance can't change later. Needs padding.
GradientMap addGradientMap({ ramp, dither, colorFactor, alpha }) Recolors by brightness through a ColorRamp.
ImageLight addImageLight(config) Image-based lighting from an environment map. See lighting.
Key addKey({ color, threshold = 0.0625, feather = 0, isolate = false }) Chroma key: removes, or keeps only, one color.
Mask addMask(mask = '__WHITE', invert = false, viewCamera, viewTransform = 'world', scaleFactor = 1) See masks-and-stencils.
NormalTools addNormalTools(config) Rotates or reshapes normal maps.
PanoramaBlur addPanoramaBlur(config) Prepares a panorama for ImageLight. Very slow.
ParallelFilters addParallelFilters() Runs its top and bottom FilterLists on the same input, then blends them.
Pixelate addPixelate(amount = 1) Mosaic. Pixel size is 2 + amount. Averages colors.
Quantize addQuantize({ steps = [8, 8, 8, 8], gamma, offset, dither = false, mode = 0 }) Fewer colors. mode 1 is HSVA.
Sampler addSampler(callback, region = null) Reads pixels back to the CPU. Draws nothing. Expensive.
Shadow addShadow(x = 0, y = 0, decay = 0.1, power = 1, color = 0x000000, samples = 6, intensity = 1) x, y place the light, from 0 to 1 across the texture. The shadow falls away from it. Needs padding.
Threshold addThreshold(edge1 = 0.5, edge2 = 0.5, invert = false) Each argument can be an RGBA array.
Vignette addVignette(x = 0.5, y = 0.5, radius = 0.5, strength = 0.5, color = 0x000000, blendMode = NORMAL) Only NORMAL, ADD, MULTIPLY and SCREEN.
Wipe addWipe(wipeWidth = 0.1, direction = 0, axis = 0, reveal = 0, wipeTexture = '__DEFAULT') Transition. Tween its progress from 0 to 1.

The Glow defaults for quality and distance come from the game config: filters: { glow: { quality: 10, distance: 10 } }.

Recipes

Bloom and shine are Actions, which add several filters for you. They return an array, one entry per target:

//  Bloom on the whole screen, in the external list. Returns { parallelFilters, threshold, blur } per target.
const [ bloom ] = Phaser.Actions.AddEffectBloom(this.cameras.main, { threshold: 0.6, blurRadius: 4 });

bloom.parallelFilters.active = false;                              //  turn it off
this.cameras.main.filters.external.remove(bloom.parallelFilters);  //  or remove it

//  A moving highlight across an image. Returns { gradient, dynamicTexture, tween, parallelFilters, blendFilter }.
const logo = this.add.image(this.scale.width / 2, 200, 'logo');

Phaser.Actions.AddEffectShine(logo, { duration: 1500, yoyo: true });

Both call enableFilters() on a Game Object and then read its filters, so they throw on a Game Object in Canvas. Guard them.

Build your own bloom, or any split-and-combine effect, with ParallelFilters:

const pf = this.cameras.main.filters.internal.addParallelFilters();

pf.top.addThreshold(0.5, 1);
pf.top.addBlur(1);
pf.blend.blendMode = Phaser.BlendModes.ADD;
pf.blend.amount = 0.5;

Color grading. Each preset replaces the matrix, unless its last argument, multiply, is true:

const cm = this.cameras.main.filters.internal.addColorMatrix();

cm.colorMatrix.grayscale(1);
cm.colorMatrix.brightness(0.8, true);   //  combined with the grayscale

Presets on colorMatrix: brightness, saturate, desaturate, hue, grayscale, blackWhite, black, contrast, negative, desaturateLuminance, sepia, night, lsd, brown, vintagePinhole, kodachrome, technicolor, polaroid, shiftToBGR, the alpha and brightness swaps, and reset(). See src/display/ColorMatrix.js.

A wipe to black, then the next Scene:

const wipe = this.cameras.main.filters.external.addWipe(0.1);

this.tweens.add({
    targets: wipe,
    progress: 1,
    duration: 1000,
    onComplete: () => this.scene.start('Level2')
});

setLeftToRight(), setRightToLeft(), setTopToBottom() and setBottomToTop() set the direction. setWipeEffect() and setRevealEffect() reset progress to 0, and setRevealEffect() also resets the texture, so call setTexture(key) after it.

Blur what's behind a pause menu: put the game in a Layer and filter that, so the menu stays sharp.

const world = this.add.layer();     //  add the game's objects to this
const menu = this.add.container();  //  the menu stays outside it

world.enableFilters();
world.filters.internal.addBlur(1, 2, 2, 1);

CaptureFrame (WebGL only) copies everything drawn before it into a texture, so a later object can show it with filters, such as a rippling water surface. It must be inside a framebuffer: a Camera with forceComposite or filters, a filtered Container, or a Dynamic Texture.

const { width, height } = this.scale;

this.cameras.main.setForceComposite(true);   //  CaptureFrame needs a framebuffer

this.add.image(width / 2, height / 2, 'background');   //  drawn before the CaptureFrame, so captured
this.add.captureFrame('sceneSoFar');

//  Drawn after it, showing the captured texture. 'waves' is a loaded displacement map.
const water = this.add.image(width / 2, height / 2, 'sceneSoFar').setAlpha(0.5).enableFilters();

water.filters.internal.addDisplacement('waves', 0.01, 0.01);

Masks and custom filters

  • Masking is done with the Mask filter, filters.internal.addMask(textureKeyOrGameObject), or with a Stencil. See masks-and-stencils.
  • A custom filter is a Controller subclass and a render node. See custom-rendering.

Performance

  • Each object with an active filter renders to a framebuffer, plus one pass per filter. Framebuffers are pooled and reused.
  • To filter many objects the same way, put them in a Layer or Container and filter that once.
  • External filters, and objects which focus on the context, use a texture the size of the screen.
  • Set renderFilters = false, or setActive(false) on a Controller, to pause filters without rebuilding them.
  • Filters never use mipmaps (4.1).

Gotchas

  • obj.filters is null until enableFilters(), and stays null in Canvas.
  • Glow, Blur, Shadow, Displacement and Bokeh are clipped at the object's edges until you call setPaddingOverride(null).
  • The padding edges are left, top, right, bottom: grow with (-n, -n, n, n).
  • Glow quality and distance are fixed when it's created. Make a new one to change them.
  • A Controller belongs to one Camera. Don't share it between objects unless ignoreDestroy is true, and then destroy it yourself.
  • addQuantize returns the Quantize Controller. Its JSDoc says it returns this.
  • Shapes, Graphics, unsized Containers and Layers render internal filters at Camera size. Expect screen-space results and screen-sized cost.
  • Filters cost draw calls and GPU memory. Test early on your target devices.

From v3

  • obj.preFX.addGlow() is obj.enableFilters() then obj.filters.internal.addGlow(). postFX is filters.external. A Camera's postFX is camera.filters.internal or external.
  • The v3 Bloom, Shine, Circle and Gradient FX are now Phaser.Actions.AddEffectBloom, AddEffectShine, AddMaskShape and the Gradient Game Object.
  • Glow quality is an integer, default 10, not a fraction. scale is a new argument, before knockout.
  • ColorMatrix presets moved to its colorMatrix property: cm.colorMatrix.sepia().
  • The full v3 to v4 tables are in v3-to-v4-migration.