Documentation/d2d
namespaceWORKER

d2d

jsdoc/d2d.js:1

Functions for working with Direct2D graphics.

Direct2D 1.1 or later is required.
Minimum OS requirements: Windows 8+ or Windows 7 Service Pack 1 with the Platform Update for Windows 7 installed.
methodWORKER

Brush

jsdoc/d2d.js:11
Brush(type, param1, param2, param3, param4)

Creates a drawing brush of the specified type. The meaning of the brush's input parameters depends on its type.
For type == BrushType.Solid:
- param1: brush colour in ARGB
For type == BrushType.LinearGradient:
- param1: start point coords of linear gradient in form of Array(2) (for ex.: [0, 0])
- param2: end point coords of linear gradient in form of Array(2) (for ex.: [100, 0])
- param3: gradient stops specified as an array with alternating position and color values for each stop (for ex.: [0.0, 0xFF000000, 0.5, 0xFFFF0000, 1.0, 0xFFFFFFFF])
- param4: wrap mode responsible for how the gradient is repeated when drawing. See BrushWrapMode. Default is BrushWrapMode.Tile
For type == BrushType.RadialGradient:
- param1: center point coords of radial gradient in form of Array(2) (for ex.: [50, 50])
- param2: radius values for X and Y axes in form of Array(2) (for ex.: [50, 50])
- param3: gradient stops specified as an array with alternating position and color values for each stop (for ex.: [0.0, 0xFF000000, 0.5, 0xFFFF0000, 1.0, 0xFFFFFFFF])
- param4: wrap mode responsible for how the gradient is repeated when drawing. See BrushWrapMode. Default is BrushWrapMode.Tile
For type == BrushType.Bitmap:
- param1: D2DBitmap object used for drawing by brush
- param2: wrap mode responsible for how the image is repeated when drawing. See BrushWrapMode

Parameters

NameTypeDescription
typeBrushType
param1*
param2 = undefinedoptional*
param3 = undefinedoptional*
param4 = undefinedoptional*

Returns

D2DBrush —

Brush object used in Draw/Fill methods

Throws

Error —

If the Direct2D host is unavailable, Direct2D resources have not been initialized, or the brush parameters are invalid.

Example source

methodWORKER

Compile

jsdoc/d2d.js:181
Compile(source, entryPoint, target, flags)

Compiles a Direct2D HLSL shader synchronously. The call blocks its JavaScript thread until compilation completes; for complex shaders or collections of presets, prefer CompileAsync. Both methods use the same native HLSL compiler and result format. They compile on every call and do not use the automatic shader cache exposed by vis.ShaderCacheStats.

Parameters

NameTypeDescription
sourcestring

Shader source code (ASCII HLSL code)

entryPoint = "main"optionalstring

The name of the shader entry point function where shader execution begins.

target = "ps_4_0"optionalstring

A string that specifies the shader target or set of shader features to compile against.
The shader target can be shader model 2, shader model 3, shader model 4, or shader model 5.
For full target list see https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/specifying-compiler-targets
Default value: "ps_4_0".

flags = 0x8008optionalD2DCompileFlags

Affects compiler flags. D2DCompileFlags
For flags values see: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/d3dcompile-constants
Default value: D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_PACK_MATRIX_ROW_MAJOR
Example for debug build: D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION | D3DCOMPILE_ALL_RESOURCES_BOUND | D3DCOMPILE_PACK_MATRIX_ROW_MAJOR

Returns

D2DCompileInfo —

Result of compiling shader source. HLSL compiler failures return a nonempty D2DCompileInfo.Error field; inspect it before using D2DCompileInfo.Code.

Throws

Error —

If the Direct2D host is unavailable or Direct2D resources have not been initialized.

Example

include(`${fb.ComponentPath}\\docs\\Effects.js`);

window.DrawMode = 1;

// Simple colour inversion shader
const shaderSource = `
    // Input texture (Direct2D passed it into t0)
    Texture2D InputTexture : register(t0);
    SamplerState InputSampler : register(s0);

    // Direct2D input data structure
    struct VS_OUTPUT {
        float4 clipSpacePos : SV_POSITION;
        float4 sceneSpacePos : SCENE_POS;
        float4 texelSpacePos : TEXEL_POS;
    };

    // Simple color inversion shader
    float4 main(VS_OUTPUT input) : SV_Target
    {
        // Selecting a pixel from an input image
        float4 color = InputTexture.Sample(InputSampler, input.texelSpacePos.xy);
	
        // Invert RGB, keep alpha
        return float4((1.0 - color.rgb) * color.a, color.a);
    }
`;

const img = d2d.Image(`${fb.ComponentPath}\\samples\\d2d\\images\\Flowers.jpg`);
const effect = d2d.Effect(Effects.CustomShader.ID);
effect.SetInput(0, img);

const shaderCode = d2d.Compile(shaderSource);
if (shaderCode.Error !== "") 
    fb.ShowPopupMessage(shaderCode.Error, "Direct2D compile error!");
else
    effect.SetValue(Effects.CustomShader.ShaderCode, shaderCode.Code);

function on_paint(dgr) {	
    dgr.DrawEffect(effect, 10, 10, 0, 0, img.Width, img.Height);
}

See also

methodWORKER

CompileAsync

jsdoc/d2d.js:246
CompileAsync(source, entryPoint, target, flags)

Compiles HLSL asynchronously on JSplitter's shared background thread pool, without blocking the panel or Worker JavaScript thread. Arguments and defaults are identical to Compile. Returns a Promise resolving to D2DCompileInfo with a Uint8Array Code and string Error. An HLSL compilation error resolves with a nonempty D2DCompileInfo.Error, just like synchronous Compile(); setup or task failures reject the Promise. This differs from vis.CreateAsync, whose shader compilation failures reject its Promise.

The produced DXBC can be reused in vis.CreateAsync or in a Direct2D CustomShader effect. Explicit CompileAsync calls compile on every call and do not use the automatic shader cache exposed by vis.ShaderCacheStats; that cache is for CreateAsync HLSL stages. The method also works inside a Worker when Direct2D is available there.

Parameters

NameTypeDescription
sourcestring

Shader source code (ASCII HLSL code).

entryPoint = "main"optionalstring

HLSL entry point.

target = "ps_4_0"optionalstring

Compiler target/profile. See https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/specifying-compiler-targets.

flags = 0x8008optionalD2DCompileFlags

D3DCompile flags, as for Compile. See D2DCompileFlags.

Returns

Promise<D2DCompileInfo> —

Promise resolving to compiled bytecode or a compiler error.

Example

// HLSL stored in shaderSource; safe to run while the panel paints.
async function prepareShader() {
    const compiled = await d2d.CompileAsync(shaderSource);
    if (compiled.Error) throw new Error(compiled.Error);
    return compiled.Code; // Uint8Array: can be reused by CreateAsync().
}

See also

methodWORKER

CreateImage

jsdoc/d2d.js:55
CreateImage(w, h)

Parameters

NameTypeDescription
wnumber
hnumber

Returns

D2DBitmap

Throws

Error —

If the Direct2D host is unavailable or Direct2D resources have not been initialized.

methodWORKER

CreateImageFromPixelData

jsdoc/d2d.js:64
CreateImageFromPixelData(pixelData, width, height, format = "bgra32")

Create D2DBitmap from raw pixel data in memory.

Parameters

NameTypeDescription
pixelDataUint8Array

Raw pixel bytes

widthnumber

Image width in pixels

heightnumber

Image height in pixels

format = "bgra32"optionalstring

Pixel format string (default: "bgra32") Supported formats:
"bgra32" 32bpp BGRA
"rgba32" 32bpp RGBA
"bgr24" 24bpp BGR
"rgb24" 24bpp RGB

Returns

D2DBitmap —

null if was an error (for example pixelData array length is not suitable for the specified parameters)

Throws

Error —

If the Direct2D host is unavailable, Direct2D resources have not been initialized, or data is not a non-empty Uint8Array.

Example source

methodWORKER

Effect

jsdoc/d2d.js:172
Effect(CLSID)

Creates Direct2D effect.

Parameters

NameTypeDescription
CLSIDstring

CLSID of Direct2D effect. See Effects for effects' CLSID.

Returns

D2DEffect

Throws

Error —

If the Direct2D host is unavailable or Direct2D resources have not been initialized.

methodWORKER

Font

jsdoc/d2d.js:84
Font(name, size_px, style)

Performance note: avoid using inside on_paint.
Performance note II: try caching and reusing D2DFont objects, since the maximum amount of such objects is hard-limited by Windows. D2DFont creation will fail after reaching this limit.

Parameters

NameTypeDescription
namestring
size_pxnumber

See Point2Pixel function for conversions

style = 0optionalnumber

See FontStyle flags

Returns

?D2DFont —

null, if font is not present.

Throws

Error —

If the Direct2D host is unavailable or Direct2D resources have not been initialized.

methodWORKER

Image

jsdoc/d2d.js:99
Image(path)

Load image from file.

Performance note: consider using LoadImageAsync or LoadImageAsyncV2 if there are a lot of images to load or if the image is big.

Relative filesystem paths are resolved as described in utils.ReadTextFile.

Parameters

NameTypeDescription
pathstring

Returns

?D2DBitmap —

null, if image failed to load.

Throws

Error —

If the Direct2D host is unavailable or Direct2D resources have not been initialized.

Example

let img = d2d.Image('e:\\images folder\\my_image.png');
methodWORKER

LoadImageAsync

jsdoc/d2d.js:117
LoadImageAsync(window_id, path)

Load image from file asynchronously.

Relative filesystem paths are resolved as described in utils.ReadTextFile.

Parameters

NameTypeDescription
window_idnumber

unused

pathstring

Returns

number —

a unique id, which is used in on_load_image_done.

Throws

Error —

If the panel host is unavailable, Direct2D resources have not been initialized, or foobar2000 is not fully initialized.

Example source

methodWORKER

LoadImageAsyncV2

jsdoc/d2d.js:132
LoadImageAsyncV2(window_id, path)

Load image from file asynchronously. Returns a Promise object, which will be resolved when image loading is done.

Relative filesystem paths are resolved as described in utils.ReadTextFile.

Parameters

NameTypeDescription
window_idnumber

unused

pathstring

Returns

Promise.<?D2DBitmap>

Throws

Error —

If the panel host is unavailable, Direct2D resources have not been initialized, or foobar2000 is not fully initialized.

Example source

methodWORKER

LoadSVG

jsdoc/d2d.js:148
LoadSVG(path_or_xml, max_width)

Loads rasterized image from SVG file or XML string

Relative filesystem paths are resolved as described in utils.ReadTextFile. Raw SVG/XML strings are used as-is.

Parameters

NameTypeDescription
path_or_xmlstring

string containing SVG file path or raw XML

max_width = 0optionalnumber

If specified rasterizes with width = max_width and height according to the proportions, otherwise uses "width" and "height" attributes in SVG header if exist

Returns

?D2DBitmap —

Rasterized bitmap, null in case of error

Throws

Error —

If the Direct2D host is unavailable or Direct2D resources have not been initialized.

Example

const svg_file = fb.ComponentPath + 'samples\\svg\\android.svg';

const original = d2d.LoadSVG(svg_file);
const large = d2d.LoadSVG(svg_file, 512); // set optional max_width

function on_paint(gr) {
    gr.DrawImage(original, 0, 0, original.Width, original.Height, 0, 0, original.Width, original.Height);
    gr.DrawImage(large, original.Width, 0, large.Width, large.Height, 0, 0, large.Width, large.Height);
}
methodWORKER

StrokeStyle

jsdoc/d2d.js:42
StrokeStyle(options)

Creates a reusable Direct2D stroke style for line and outline drawing.
The style controls start/end/dash caps, line joins, miter limit, dash pattern and dash offset.
Performance note: create commonly used styles once and reuse them from on_paint.

Dotted strokes: when dashCap is omitted, DashStyle.Dot, DashStyle.DashDot and DashStyle.DashDotDot automatically use CapStyle.Round. Setting dashStyle to DashStyle.Dot in StrokeStyle therefore matches the DashStyle.Dot drawing-method shorthand. An explicitly supplied dashCap is preserved, including CapStyle.Flat. See Microsoft: D2D1_DASH_STYLE and Microsoft: D2D1_CAP_STYLE.

Parameters

NameTypeDescription
options = {}optionalD2DStrokeStyleOptions

Stroke appearance options. Omitted properties use the defaults documented by D2DStrokeStyleOptions.

Returns

D2DStrokeStyle

Throws

Error —

If the Direct2D host is unavailable, Direct2D resources have not been initialized, or the stroke-style options are invalid.

Example source