melonJS
    Preparing search index...

    Class Renderer

    a base renderer object

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    _litPipelineWarned: boolean | undefined
    activeLightCount: number

    Number of active Light2d instances uploaded to the lit batcher for the current frame. Set by setLightUniforms. The WebGL renderer's drawImage reads this to decide between the unlit fast-path batcher (default) and the lit batcher (only when lights AND a normal map are both in play).

    backgroundColor: Color

    The background color used to clear the main framebuffer. Note: alpha value will be set based on the transparent property of the renderer settings.

    black
    
    currentColor: Color
    currentNormalMap:
        | ImageBitmap
        | HTMLImageElement
        | HTMLCanvasElement
        | OffscreenCanvas
        | null

    The normal-map texture associated with the next drawImage call, if any. Set by Sprite.draw (and any other normal-map-aware renderable) just before calling drawImage, then cleared back to null after. The WebGL renderer reads this state and routes lit quads through the shader's lighting path; the Canvas renderer ignores it entirely.

    currentScissor: Int32Array<ArrayBufferLike>
    currentTint: Color
    designRatio: number

    the requested video size ratio

    GPURenderer: string | undefined

    The GPU renderer string (WebGL only, undefined for Canvas)

    isContextValid: boolean

    true if the current rendering context is valid

    true
    
    lineWidth: number

    The thickness of lines for shape drawing operations like Renderer#strokeRect, Renderer#strokeEllipse and Renderer#strokeLine. Subclasses override the storage — CanvasRenderer proxies it to the underlying 2D context via a getter/setter, while WebGLRenderer treats it as a regular field consumed by its shape-stroke routines.

    1
    
    path2D: Path2D

    The Path2D instance used by the renderer to draw primitives

    projectionMatrix: Matrix3d
    renderState: RenderState

    The renderer state container (color, tint, transform, scissor, blend mode) with a zero-allocation save/restore stack.

    renderTarget: CanvasRenderTarget

    The renderer renderTarget

    renderTarget

    scaleRatio: Vector2d

    the scaling ratio to be applied to the main canvas

    <1,1>
    
    settings: object

    The given constructor options

    type: string

    The renderer type : Canvas, WebGL, etc... (override this property with a specific value when implementing a custom renderer)

    uvOffset: number
    _whitePixel: any

    Accessors

    • get currentDepth(): number

      Current per-renderable depth value. WebGL batchers push it into the vertex stream as the z component of each vertex — a no-op under the default orthographic projection, used by perspective (Camera3d) to scale and parallax sprites by distance. Mirrors renderable.depth, set automatically by Renderable.preDraw via Renderer#setDepth.

      Returns number

      0
      
    • set currentDepth(value: number): void

      Parameters

      • value: number

      Returns void

    Methods

    • Blit a texture to the screen through a shader effect. Draws a screen-aligned quad using the given texture as source and the given shader for post-processing (e.g. scanlines, desaturation). No-op on Canvas renderer.

      Parameters

      • source: WebGLTexture

        the source texture to blit

      • x: number

        destination x position

      • y: number

        destination y position

      • width: number

        destination width

      • height: number

        destination height

      • shader: ShaderEffect

        the shader effect to apply

      • OptionalkeepBlend: boolean

        if true, keep current blend mode (for sprite compositing)

      Returns void

    • Clear the current render target to transparent black (color + stencil). Used to prepare FBOs for post-effect capture. No-op on Canvas renderer.

      Returns void

    • Create a linear gradient that can be used with Renderer#setColor.

      Parameters

      • x0: number

        x-axis coordinate of the start point

      • y0: number

        y-axis coordinate of the start point

      • x1: number

        x-axis coordinate of the end point

      • y1: number

        y-axis coordinate of the end point

      Returns Gradient

      a Gradient object

    • Create a radial gradient that can be used with Renderer#setColor.

      Parameters

      • x0: number

        x-axis coordinate of the start circle

      • y0: number

        y-axis coordinate of the start circle

      • r0: number

        radius of the start circle

      • x1: number

        x-axis coordinate of the end circle

      • y1: number

        y-axis coordinate of the end circle

      • r1: number

        radius of the end circle

      Returns Gradient

      a Gradient object

    • Draw an image or sub-image into the framebuffer. Implemented by subclasses (CanvasRenderer / WebGLRenderer).

      The 9-argument signature shown here is the canonical form used throughout the engine; the concrete renderers also accept the shorter drawImage(image, dx, dy) and drawImage(image, dx, dy, dWidth, dHeight) variants from the HTML Canvas2D spec.

      Parameters

      • image:
            | ImageBitmap
            | HTMLImageElement
            | HTMLVideoElement
            | VideoFrame
            | HTMLCanvasElement
            | OffscreenCanvas
            | SVGImageElement

        the source image

      • sx: number

        source rectangle left

      • sy: number

        source rectangle top

      • sw: number

        source rectangle width

      • sh: number

        source rectangle height

      • dx: number

        destination left

      • dy: number

        destination top

      • dw: number

        destination width

      • dh: number

        destination height

      Returns void

    • Render a Light2d instance.

      Each renderer implements its own strategy: the WebGL renderer draws lights as quads through a shared procedural radial-falloff fragment shader (no per-light texture, color and intensity encoded in the per-vertex tint so consecutive draws batch); the Canvas renderer caches a small Gradient config object per light in a WeakMap (rebuilt only when the light's radii / color / intensity change), rasterizes it with Gradient.toCanvas() into a single shared CanvasRenderTarget, and composites the result via drawImage. The base implementation is a no-op so renderers without a lighting path can be polymorphically substituted.

      Light2d itself is renderer-agnostic — it just calls renderer.drawLight(this) and relies on the renderer to pick the right machinery.

      Parameters

      • light: object

        the Light2d instance to render

      Returns void

      Light2d

    • Draw a textured triangle mesh. The mesh object must provide: vertices (Float32Array, x/y/z triplets), uvs (Float32Array, u/v pairs), indices (Uint16Array, triangle indices), texture (TextureAtlas), vertexCount (number), and optionally cullBackFaces (boolean, default true). WebGL uses hardware depth testing; Canvas uses painter's algorithm (back-to-front sort).

      Parameters

      • mesh: Mesh

        a Mesh renderable or compatible object

      Returns void

    • Draw a TMX tile layer. Default behavior:

      • if layer.canvasRenderer is set (preRender bake), blit the cached offscreen canvas in a single drawImage call;
      • otherwise delegate to the layer's TMX orientation renderer for the per-tile loop.

      WebGLRenderer overrides this to add the procedural shader fast path on top (when layer.renderMode === "shader") and fall through to this base behavior for all other layers.

      Parameters

      • layer: object

        the TMXLayer to draw

      • rect: Rect

        the visible region in world coords

      Returns void

    • Enable the scissor test with the given rectangle. No-op on Canvas renderer.

      Parameters

      • x: number

        x coordinate of the scissor rectangle

      • y: number

        y coordinate of the scissor rectangle

      • width: number

        width of the scissor rectangle

      • height: number

        height of the scissor rectangle

      Returns void

    • Fill an axis-aligned ellipse with the current color. Implemented by subclasses.

      Parameters

      • x: number

        ellipse center X in viewport pixels

      • y: number

        ellipse center Y in viewport pixels

      • w: number

        horizontal radius

      • h: number

        vertical radius

      Returns void

    • Fill an axis-aligned rectangle with the current color. Implemented by subclasses.

      Parameters

      • x: number

        left edge in viewport pixels

      • y: number

        top edge in viewport pixels

      • width: number

        rectangle width

      • height: number

        rectangle height

      Returns void

    • return a reference to the current render target corresponding Context

      Returns CanvasRenderingContext2D | WebGLRenderingContext

    • return the list of supported compressed texture formats. The base implementation returns null for all formats (no GPU compressed texture support). The WebGL renderer overrides this with actual extension availability.

      Returns Object

      an object with one key per extension family, each value is the WebGL extension object or null

    • return true if the given compressed texture format is supported

      Parameters

      • format: number

        a WebGL compressed texture format constant

      Returns boolean

    • resizes the system canvas

      Parameters

      • width: number

        new width of the canvas

      • height: number

        new height of the canvas

      Returns void

    • Rotate the current transform by angle (radians). Implemented by subclasses.

      Parameters

      • angle: number

        rotation angle in radians

      Returns void

    • Scale the current transform by (x, y). Implemented by subclasses.

      Parameters

      • x: number

        horizontal scale factor

      • y: number

        vertical scale factor

      Returns void

    • enable/disable image smoothing (scaling interpolation) for the current render target

      Parameters

      • Optionalenable: boolean = false

      Returns void

    • Enable or disable alpha blending. No-op on Canvas renderer (Canvas always blends).

      Parameters

      • enable: boolean

        true to enable blending, false to disable

      Returns void

    • set the current blend mode. Subclasses (CanvasRenderer, WebGLRenderer) implement the actual GL/Canvas logic.

      Parameters

      • Optionalmode: string = "normal"

        blend mode

      Returns void

    • Set the current per-renderable depth value. WebGL batchers push it into the vertex stream as the z component of each vertex — a no-op under the default orthographic projection, used by perspective (Camera3d) to scale and parallax sprites by distance.

      Typically called automatically by Renderable.preDraw from the renderable's depth property. User code only needs to call this directly when emitting draw calls outside of a Renderable.draw() — e.g. from a custom Container.draw() override.

      Honored by the save/restore stack like setTint / setColor.

      Parameters

      • depth: number

        the depth value to set

      Returns void

      Renderable#depth

    • Set the renderer global alpha (0..1) for subsequent draw calls. Implemented by subclasses.

      Parameters

      • alpha: number

        opacity value in the [0..1] range

      Returns void

    • Upload the active scene lights to the lit sprite pipeline.

      Called once per camera per frame by Camera2d.draw() (after the FBO is bound, before the world tree walk fires Sprite.draw for any normal-mapped sprite). The WebGL renderer overrides this to pack the lights into the lit shader's uniform buffers; the Canvas renderer cannot do per-pixel normal-map lighting and silently ignores the call. The first time a non-empty light list is passed in Canvas mode, a one-shot console warning is emitted.

      Stage stays renderer-agnostic by passing the raw scene data — lights iterable and ambient color — and letting the renderer decide how to encode them.

      Parameters

      • Optionallights: Iterable<object, any, any>

        active Light2d instances; falsy/empty no-ops

      • Optionalambient: object

        ambient lighting color (0..255 RGB)

      • OptionaltranslateX: number

        world-to-screen X translate (matches Camera2d.draw())

      • OptionaltranslateY: number

        world-to-screen Y translate

      Returns void

    • Set the line dash pattern for stroke operations.

      Parameters

      • segments: number[]

        an array of numbers specifying distances to alternately draw a line and a gap. An empty array clears the dash pattern (solid lines).

      Returns void

      // draw a dashed line
      renderer.setLineDash([10, 5]);
      renderer.strokeLine(0, 0, 100, 0);
      // clear the dash pattern
      renderer.setLineDash([]);
    • A mask limits rendering elements to the shape and position of the given mask object. So, if the renderable is larger than the mask, only the intersecting part of the renderable will be visible. Mask are not preserved through renderer context save and restore.

      Returns void

    • set a coloring tint for sprite based renderables

      Parameters

      • tint: Color

        the tint color

      • Optionalalpha: number = tint.alpha

        an alpha value to be applied to the tint

      Returns void

    • Sets the viewport for the renderer. Defines the affine transformation from normalized device coordinates to window coordinates. No-op on Canvas renderer.

      Parameters

      • Optionalx: number = 0

        x coordinate of the viewport origin

      • Optionaly: number = 0

        y coordinate of the viewport origin

      • Optionalw: number

        width of the viewport (defaults to canvas width)

      • Optionalh: number

        height of the viewport (defaults to canvas height)

      Returns void

    • Stroke (outline) an axis-aligned ellipse with the current color at the current Renderer#lineWidth. Implemented by subclasses.

      Parameters

      • x: number

        ellipse center X in viewport pixels

      • y: number

        ellipse center Y in viewport pixels

      • w: number

        horizontal radius

      • h: number

        vertical radius

      • Optionalfill: boolean

        also fill the ellipse

      Returns void

    • Draw a straight line between two points with the current color at the current Renderer#lineWidth. Implemented by subclasses.

      Parameters

      • startX: number

        start X in viewport pixels

      • startY: number

        start Y in viewport pixels

      • endX: number

        end X in viewport pixels

      • endY: number

        end Y in viewport pixels

      Returns void

    • Stroke (outline) an axis-aligned rectangle with the current color at the current Renderer#lineWidth. Implemented by subclasses.

      Parameters

      • x: number

        left edge in viewport pixels

      • y: number

        top edge in viewport pixels

      • width: number

        rectangle width

      • height: number

        rectangle height

      • Optionalfill: boolean

        also fill the rectangle

      Returns void

    • tint the given image or canvas using the given color

      Parameters

      • src: HTMLImageElement | HTMLCanvasElement | OffscreenCanvas

        the source image to be tinted

      • color: string | Color

        the color that will be used to tint the image

      • Optionalmode: string = "multiply"

        the composition mode used to tint the image

      Returns HTMLCanvasElement | OffscreenCanvas

      a new canvas or offscreencanvas (if supported) element representing the tinted image

    • creates a Blob object representing the last rendered frame

      Parameters

      • Optionaltype: string = "image/png"

        A string indicating the image format

      • Optionalquality: number

        A Number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.

      Returns Promise<any>

      A Promise returning a Blob object representing the last rendered frame

      renderer.convertToBlob().then((blob) => console.log(blob));
      
    • returns a data URL containing a representation of the last frame rendered

      Parameters

      • Optionaltype: string = "image/png"

        A string indicating the image format

      • Optionalquality: number

        A Number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.

      Returns Promise<any>

      A Promise returning a string containing the requested data URL.

      renderer.toDataURL().then((dataURL) => console.log(dataURL));
      
    • creates an ImageBitmap object of the last frame rendered (not supported by standard Canvas)

      Parameters

      • Optionaltype: string = "image/png"

        A string indicating the image format

      • Optionalquality: number

        A Number between 0 and 1 indicating the image quality to be used when creating images using file formats that support lossy compression (such as image/jpeg or image/webp). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.

      Returns Promise<any>

      A Promise returning an ImageBitmap.

      renderer.transferToImageBitmap().then((image) => console.log(image));
      
    • Translate the current transform by (x, y). Implemented by subclasses.

      Parameters

      • x: number

        horizontal translation in pixels

      • y: number

        vertical translation in pixels

      Returns void

    • Create and return a new Canvas element (or OffscreenCanvas when supported and returnOffscreenCanvas is true). Centralized renderer-side allocator so every scratch / fallback / render- target canvas in the engine routes through the same OffscreenCanvas-aware path, instead of duplicating document.createElement calls that throw in worker contexts.

      Parameters

      • width: number

        canvas width in pixels

      • height: number

        canvas height in pixels

      • OptionalreturnOffscreenCanvas: boolean = false

        return an OffscreenCanvas if the platform supports it

      Returns HTMLCanvasElement | OffscreenCanvas

      a new canvas of the given size

    • Shared 1×1 fully-white canvas used as a no-op texture fallback. Renderers and renderables that need a "blank" texture binding (e.g. to satisfy a shader's sampler input when there's no real image — Kd-only Mesh materials, solid-color quad fills, etc.) should use this rather than allocating their own.

      Lazily created on first call; shared across every caller; uses OffscreenCanvas where supported (worker-safe). Static so it's accessible without a renderer instance (e.g. from a Mesh constructor that runs before the active renderer is set).

      Returns HTMLCanvasElement | OffscreenCanvas

      the shared 1×1 white canvas