# CameraComponent

Class · extends [`Component`](https://api.playcanvas.com/engine/classes/Component.md) · category: Graphics

Source: https://github.com/playcanvas/engine/blob/970d89f6d3bc6667f4e1f88153abd6e7e82ed52c/src/framework/components/camera/component.js#L78

The CameraComponent enables an [Entity](https://api.playcanvas.com/engine/classes/Entity.md) to render the scene. A scene requires at least
one enabled camera component to be rendered. The camera's view direction is along the negative
z-axis of the owner entity.

Note that multiple camera components can be enabled simultaneously (for split-screen or
offscreen rendering, for example).

You should never need to use the CameraComponent constructor directly. To add a CameraComponent
to an [Entity](https://api.playcanvas.com/engine/classes/Entity.md), use [Entity#addComponent](https://api.playcanvas.com/engine/classes/Entity.md#addcomponent):

```javascript
const entity = new Entity();
entity.addComponent('camera', {
    nearClip: 1,
    farClip: 100,
    fov: 55
});
```

Once the CameraComponent is added to the entity, you can access it via the [Entity#camera](https://api.playcanvas.com/engine/classes/Entity.md#camera)
property:

```javascript
entity.camera.nearClip = 2; // Set the near clip of the camera

console.log(entity.camera.nearClip); // Get the near clip of the camera
```

For ready-made camera behaviour, attach the `CameraControls` script from
`playcanvas/scripts/esm/camera-controls.mjs`, which provides orbit, fly and pan driven by mouse,
touch and gamepad input.

Relevant Engine API examples:

- [First Person Camera](https://playcanvas.github.io/#/camera/first-person)
- [Fly Camera](https://playcanvas.github.io/#/camera/fly)
- [Multiple Cameras](https://playcanvas.github.io/#/camera/multi)
- [Orbit Camera](https://playcanvas.github.io/#/camera/orbit)

## Accessors

### aperture

```ts
get aperture(): number
set aperture(value: number)
```

Gets the camera aperture in f-stops.

### aspectRatio

```ts
get aspectRatio(): number
set aspectRatio(value: number)
```

Gets the aspect ratio (width divided by height) of the camera.

### aspectRatioMode

```ts
get aspectRatioMode(): number
set aspectRatioMode(value: number)
```

Gets the aspect ratio mode of the camera.

### calculateProjection

```ts
get calculateProjection(): CalculateMatrixCallback
set calculateProjection(value: CalculateMatrixCallback)
```

Gets the custom function to calculate the camera projection matrix manually.

### calculateTransform

```ts
get calculateTransform(): CalculateMatrixCallback
set calculateTransform(value: CalculateMatrixCallback)
```

Gets the custom function to calculate the camera transformation matrix manually.

### clearColor

```ts
get clearColor(): Color
set clearColor(value: Color)
```

Gets the camera component's clear color.

### clearColorBuffer

```ts
get clearColorBuffer(): boolean
set clearColorBuffer(value: boolean)
```

Gets whether the camera will automatically clear the color buffer before rendering.

### clearDepth

```ts
get clearDepth(): number
set clearDepth(value: number)
```

Gets the depth value to clear the depth buffer to.

### clearDepthBuffer

```ts
get clearDepthBuffer(): boolean
set clearDepthBuffer(value: boolean)
```

Gets whether the camera will automatically clear the depth buffer before rendering.

### clearStencilBuffer

```ts
get clearStencilBuffer(): boolean
set clearStencilBuffer(value: boolean)
```

Gets whether the camera will automatically clear the stencil buffer before rendering.

### cullFaces

```ts
get cullFaces(): boolean
set cullFaces(value: boolean)
```

Gets whether the camera will cull triangle faces.

### disablePostEffectsLayer

```ts
get disablePostEffectsLayer(): number
set disablePostEffectsLayer(layer: number)
```

Gets the layer id of the layer on which the post-processing of the camera stops being applied
to.

### farClip

```ts
get farClip(): number
set farClip(value: number)
```

Gets the distance from the camera after which no rendering will take place.

### flipFaces

```ts
get flipFaces(): boolean
set flipFaces(value: boolean)
```

Gets whether the camera will flip the face direction of triangles.

### fog

```ts
get fog(): FogParams | null
set fog(value: FogParams | null)
```

Gets a [FogParams](https://api.playcanvas.com/engine/classes/FogParams.md) that defines fog parameters, or null if those are not set.

### fov

```ts
get fov(): number
set fov(value: number)
```

Gets the field of view of the camera in degrees.

### frustum

```ts
get frustum(): Frustum
```

Gets the camera's frustum shape.

### frustumCulling

```ts
get frustumCulling(): boolean
set frustumCulling(value: boolean)
```

Gets whether frustum culling is enabled.

### gammaCorrection

```ts
get gammaCorrection(): number
set gammaCorrection(value: number)
```

Gets the gamma correction used when rendering the scene.

### horizontalFov

```ts
get horizontalFov(): boolean
set horizontalFov(value: boolean)
```

Gets whether the camera's field of view ([fov](https://api.playcanvas.com/engine/classes/CameraComponent.md#fov)) is horizontal or vertical.

### jitter

```ts
get jitter(): number
set jitter(value: number)
```

Gets the jitter intensity applied in the projection matrix.

### layers

```ts
get layers(): readonly number[]
set layers(newValue: readonly number[])
```

Gets the array of layer IDs ([Layer#id](https://api.playcanvas.com/engine/classes/Layer.md#id)) to which this camera belongs.

### nearClip

```ts
get nearClip(): number
set nearClip(value: number)
```

Gets the distance from the camera before which no rendering will take place.

### orthoHeight

```ts
get orthoHeight(): number
set orthoHeight(value: number)
```

Gets the half-height of the orthographic view window (in the Y-axis).

### postEffects

```ts
get postEffects(): PostEffectQueue
```

Gets the post effects queue for this camera. Use this to add or remove post effects from the
camera.

### priority

```ts
get priority(): number
set priority(newValue: number)
```

Gets the priority to control the render order of this camera.

### projection

```ts
get projection(): number
set projection(value: number)
```

Gets the type of projection used to render the camera.

### projectionMatrix

```ts
get projectionMatrix(): Mat4
```

Gets the camera's projection matrix.

### projectionOffset

```ts
get projectionOffset(): Vec2
set projectionOffset(value: Vec2)
```

Gets the offset of the projection window.

### rect

```ts
get rect(): Readonly<Vec4>
set rect(value: Readonly<Vec4>)
```

Gets the rendering rectangle for the camera.

### renderTarget

```ts
get renderTarget(): RenderTarget
set renderTarget(value: RenderTarget)
```

Gets the render target to which rendering of the camera is performed.

### scissorRect

```ts
get scissorRect(): Vec4
set scissorRect(value: Vec4)
```

Gets the scissor rectangle for the camera.

### sensitivity

```ts
get sensitivity(): number
set sensitivity(value: number)
```

Gets the camera sensitivity in ISO.

### shutter

```ts
get shutter(): number
set shutter(value: number)
```

Gets the camera shutter speed in seconds.

### toneMapping

```ts
get toneMapping(): number
set toneMapping(value: number)
```

Gets the tonemapping transform applied to the rendered color buffer.

### viewMatrix

```ts
get viewMatrix(): Mat4
```

Gets the camera's view matrix.

## Methods

### calculateAspectRatio

```ts
calculateAspectRatio(rt?: RenderTarget | null): number
```

Computes the aspect ratio this camera would produce when rendering to the given render
target, without changing the camera's state. When `rt` is omitted, the camera's own
[CameraComponent#renderTarget](https://api.playcanvas.com/engine/classes/CameraComponent.md#rendertarget) is used, and if that is also null, the backbuffer
is used. The camera's [CameraComponent#rect](https://api.playcanvas.com/engine/classes/CameraComponent.md#rect) viewport is taken into account.

**Parameters**

- `rt` ([`RenderTarget`](https://api.playcanvas.com/engine/classes/RenderTarget.md) `| null`, optional): Optional render target to compute the aspect ratio
  against. Defaults to the camera's current render target, or the backbuffer if none is
  assigned.

**Returns** `number`: The computed aspect ratio.

### endXr

```ts
endXr(callback?: XrErrorCallback): void
```

Attempt to end XR session of this camera.

**Parameters**

- `callback` ([`XrErrorCallback`](https://api.playcanvas.com/engine/types/XrErrorCallback.md), optional): Optional callback function called once session is
  ended. The callback has one argument Error - it is null if successfully ended XR session.

**Example**

```ts
// On an entity with a camera component
this.entity.camera.endXr((err) => {
    // not anymore in XR
});
```

### getClearColor

```ts
getClearColor(index: number): Color
```

Gets the clear color of a color attachment of the camera's render target.

**Parameters**

- `index` (`number`): The index of the color attachment.

**Returns** [`Color`](https://api.playcanvas.com/engine/classes/Color.md): The clear color of the attachment.

### getShaderPass

```ts
getShaderPass(): string | undefined
```

Shader pass name.

**Returns** `string | undefined`: The name of the shader pass, or undefined if no shader pass is set.

### requestSceneColorMap

```ts
requestSceneColorMap(enabled: boolean): void
```

Request the scene to generate a texture containing the scene color map. Note that this call
is accumulative, and for each enable request, a disable request need to be called. Note that
this setting is ignored when `framePasses` is used.

**Parameters**

- `enabled` (`boolean`): True to request the generation, false to disable it.

### requestSceneDepthMap

```ts
requestSceneDepthMap(enabled: boolean): void
```

Request the scene to generate a texture containing the scene depth map. Note that this call
is accumulative, and for each enable request, a disable request need to be called. Note that
this setting is ignored when `framePasses` is used.

**Parameters**

- `enabled` (`boolean`): True to request the generation, false to disable it.

### screenToWorld

```ts
screenToWorld(screenx: number, screeny: number, cameraz: number, worldCoord?: Vec3): Vec3
```

Convert a point from 2D screen space to 3D world space.

**Parameters**

- `screenx` (`number`): X coordinate on PlayCanvas' canvas element. Should be in the range
  0 to `canvas.offsetWidth` of the application's canvas element.
- `screeny` (`number`): Y coordinate on PlayCanvas' canvas element. Should be in the range
  0 to `canvas.offsetHeight` of the application's canvas element.
- `cameraz` (`number`): The distance from the camera in world space to create the new
  point.
- `worldCoord` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): 3D vector to receive world coordinate result.

**Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The world space coordinate.

**Example**

```ts
// Get the start and end points of a 3D ray fired from a screen click position
const start = entity.camera.screenToWorld(clickX, clickY, entity.camera.nearClip);
const end = entity.camera.screenToWorld(clickX, clickY, entity.camera.farClip);

// Use the ray coordinates to perform a raycast
const result = app.systems.rigidbody.raycastFirst(start, end);
if (result) {
    console.log(`Entity ${result.entity.name} was selected`);
}
```

### setClearColor

```ts
setClearColor(index: number, color: Color | null): void
```

Sets the clear color of a color attachment of the camera's render target, which allows the
color buffers of a [RenderTarget](https://api.playcanvas.com/engine/classes/RenderTarget.md) with multiple color buffers to clear to different
colors. The attachment 0 clears to [CameraComponent#clearColor](https://api.playcanvas.com/engine/classes/CameraComponent.md#clearcolor), and the other
attachments clear to the same color unless given their own here. Pass null to remove the
color of an attachment, so that it clears to the attachment 0 color again. The components
of the clear color of an integer format attachment are the integer values to clear to.

**Parameters**

- `index` (`number`): The index of the color attachment.
- `color` ([`Color`](https://api.playcanvas.com/engine/classes/Color.md) `| null`): The clear color, specified in sRGB space, or null to clear to
  the color of the attachment 0.

**Example**

```ts
// clear the second color buffer of the render target to a different color
entity.camera.setClearColor(1, new pc.Color(0.5, 0.5, 1, 1));
```

### setShaderPass

```ts
setShaderPass(name: string): number
```

Sets the name of the shader pass the camera will use when rendering.

In addition to existing names (see the parameter description), a new name can be specified,
which creates a new shader pass with the given name. The name provided can only use
alphanumeric characters and underscores. When a shader is compiled for the new pass, a define
is added to the shader. For example, if the name is 'custom_rendering', the define
'CUSTOM_RENDERING_PASS' is added to the shader, allowing the shader code to conditionally
execute code only when that shader pass is active.

Another instance where this approach may prove useful is when a camera needs to render a more
cost-effective version of shaders, such as when creating a reflection texture. To accomplish
this, a callback on the material that triggers during shader compilation can be used. This
callback can modify the shader generation options specifically for this shader pass.

```javascript
const shaderPassId = camera.setShaderPass('custom_rendering');

material.onUpdateShader = function (options) {
    if (options.pass === shaderPassId) {
        options.litOptions.normalMapEnabled = false;
        options.litOptions.useSpecular = false;
    }
    return options;
};
```

**Parameters**

- `name` (`string`): The name of the shader pass. Defaults to undefined, which is
  equivalent to [SHADERPASS_FORWARD](https://api.playcanvas.com/engine/variables/SHADERPASS_FORWARD.md). Can be:

  - [SHADERPASS_FORWARD](https://api.playcanvas.com/engine/variables/SHADERPASS_FORWARD.md)
  - [SHADERPASS_ALBEDO](https://api.playcanvas.com/engine/variables/SHADERPASS_ALBEDO.md)
  - [SHADERPASS_OPACITY](https://api.playcanvas.com/engine/variables/SHADERPASS_OPACITY.md)
  - [SHADERPASS_WORLDNORMAL](https://api.playcanvas.com/engine/variables/SHADERPASS_WORLDNORMAL.md)
  - [SHADERPASS_SPECULARITY](https://api.playcanvas.com/engine/variables/SHADERPASS_SPECULARITY.md)
  - [SHADERPASS_GLOSS](https://api.playcanvas.com/engine/variables/SHADERPASS_GLOSS.md)
  - [SHADERPASS_METALNESS](https://api.playcanvas.com/engine/variables/SHADERPASS_METALNESS.md)
  - [SHADERPASS_AO](https://api.playcanvas.com/engine/variables/SHADERPASS_AO.md)
  - [SHADERPASS_EMISSION](https://api.playcanvas.com/engine/variables/SHADERPASS_EMISSION.md)
  - [SHADERPASS_LIGHTING](https://api.playcanvas.com/engine/variables/SHADERPASS_LIGHTING.md)
  - [SHADERPASS_UV0](https://api.playcanvas.com/engine/variables/SHADERPASS_UV0.md)

  The returned index can be used with [MeshInstance#shaderPassMask](https://api.playcanvas.com/engine/classes/MeshInstance.md#shaderpassmask) to control which mesh
  instances are rendered in this pass.

**Returns** `number`: The id of the shader pass.

### startXr

```ts
startXr(type: string, spaceType: string, options?: object): void
```

Attempt to start XR session with this camera.

**Parameters**

- `type` (`string`): The type of session. Can be one of the following:

  - [XRTYPE_INLINE](https://api.playcanvas.com/engine/variables/XRTYPE_INLINE.md): Inline - always available type of session. It has limited feature
  availability and is rendered into HTML element.
  - [XRTYPE_VR](https://api.playcanvas.com/engine/variables/XRTYPE_VR.md): Immersive VR - session that provides exclusive access to the VR device
  with the best available tracking features.
  - [XRTYPE_AR](https://api.playcanvas.com/engine/variables/XRTYPE_AR.md): Immersive AR - session that provides exclusive access to the VR/AR
  device that is intended to be blended with the real-world environment.
- `spaceType` (`string`): Reference space type. Can be one of the following:

  - [XRSPACE_VIEWER](https://api.playcanvas.com/engine/variables/XRSPACE_VIEWER.md): Viewer - always supported space with some basic tracking
  capabilities.
  - [XRSPACE_LOCAL](https://api.playcanvas.com/engine/variables/XRSPACE_LOCAL.md): Local - represents a tracking space with a native origin near the
  viewer at the time of creation. It is meant for seated or basic local XR sessions.
  - [XRSPACE_LOCALFLOOR](https://api.playcanvas.com/engine/variables/XRSPACE_LOCALFLOOR.md): Local Floor - represents a tracking space with a native origin
  at the floor in a safe position for the user to stand. The y-axis equals 0 at floor level.
  Floor level value might be estimated by the underlying platform. It is meant for seated or
  basic local XR sessions.
  - [XRSPACE_BOUNDEDFLOOR](https://api.playcanvas.com/engine/variables/XRSPACE_BOUNDEDFLOOR.md): Bounded Floor - represents a tracking space with its native
  origin at the floor, where the user is expected to move within a pre-established boundary.
  - [XRSPACE_UNBOUNDED](https://api.playcanvas.com/engine/variables/XRSPACE_UNBOUNDED.md): Unbounded - represents a tracking space where the user is
  expected to move freely around their environment, potentially long distances from their
  starting point.
- `options` (`object`, optional): Object with options for XR session initialization.
    - `options.anchors` (`boolean`, optional): Optional boolean to attempt to enable [XrAnchors](https://api.playcanvas.com/engine/classes/XrAnchors.md).
    - `options.callback` ([`XrErrorCallback`](https://api.playcanvas.com/engine/types/XrErrorCallback.md), optional): Optional callback function called once the
      session is started. The callback has one argument Error - it is null if the XR session
      started successfully.
    - `options.depthSensing` (`object`, optional): Optional object with parameters to attempt to enable
      depth sensing.
        - `options.depthSensing.dataFormatPreference` (`string`, optional): Optional data format
          preference for depth sensing. Can be 'luminance-alpha' or 'float32' (XRDEPTHSENSINGFORMAT_*),
          defaults to 'luminance-alpha'. Most preferred and supported will be chosen by the underlying
          depth sensing system.
        - `options.depthSensing.usagePreference` (`string`, optional): Optional usage preference for depth
          sensing, can be 'cpu-optimized' or 'gpu-optimized' (XRDEPTHSENSINGUSAGE_*), defaults to
          'cpu-optimized'. Most preferred and supported will be chosen by the underlying depth sensing
          system.
    - `options.imageTracking` (`boolean`, optional): Set to true to attempt to enable [XrImageTracking](https://api.playcanvas.com/engine/classes/XrImageTracking.md).
    - `options.optionalFeatures` (`string[]`, optional): Optional features for XRSession start. It is
      used for getting access to additional WebXR spec extensions.
    - `options.planeDetection` (`boolean`, optional): Set to true to attempt to enable [XrPlaneDetection](https://api.playcanvas.com/engine/classes/XrPlaneDetection.md).

**Example**

```ts
// On an entity with a camera component
this.entity.camera.startXr(XRTYPE_VR, XRSPACE_LOCAL, {
    callback: (err) => {
        if (err) {
            // failed to start XR session
        } else {
            // in XR
        }
    }
});
```

### worldToScreen

```ts
worldToScreen(worldCoord: Vec3, screenCoord?: Vec3): Vec3
```

Convert a point from 3D world space to 2D screen space.

The returned `z` is the unnormalized clip space depth, not a behind-the-camera flag: it also
goes negative for points in front of a perspective camera that are nearer than twice the
near clip, and for an orthographic camera it is negative across the whole near half of the
depth range. To reject points behind the camera, test the view space depth instead - pass
the world position through [CameraComponent#viewMatrix](https://api.playcanvas.com/engine/classes/CameraComponent.md#viewmatrix) and discard it when the
resulting `z` is zero or greater.

**Parameters**

- `worldCoord` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md)): The world space coordinate.
- `screenCoord` ([`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md), optional): 3D vector to receive screen coordinate result.

**Returns** [`Vec3`](https://api.playcanvas.com/engine/classes/Vec3.md): The screen space coordinate.

## Inherited from [Component](https://api.playcanvas.com/engine/classes/Component.md)

- `entity: Entity`
- `system: ComponentSystem`
- `get enabled(): boolean` · `set enabled(value: boolean)`
- `fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler`
- `hasEvent(name: string): boolean`
- `off(name?: string, callback?: HandleEventCallback, scope?: any): EventHandler`
- `on(name: string, callback: HandleEventCallback, scope?: any): EventHandle`
- `once(name: string, callback: HandleEventCallback, scope?: any): EventHandle`
