Skip to main content

Class: Niivue

Defined in: niivue/index.ts:364

Niivue can be attached to a canvas. An instance of Niivue contains methods for loading and rendering NIFTI image data in a WebGL 2.0 context.

Example

let niivue = new Niivue({ crosshairColor: [0, 1, 0, 0.5], textHeight: 0.5 }); // a see-through green crosshair, and larger text labels

Constructors

Constructor

new Niivue(options: Partial<NVConfigOptions>): Niivue;

Defined in: niivue/index.ts:889

Parameters

ParameterTypeDefault valueDescription
optionsPartial<NVConfigOptions>DEFAULT_OPTIONSoptions object to set modifiable Niivue properties

Returns

Niivue

Properties

PropertyTypeDefault valueDescriptionDefined in
_glWebGL2RenderingContextnull-niivue/index.ts:377
backNVImagenull-niivue/index.ts:514
backgroundMasksOverlaysnumber0-niivue/index.ts:456
blurShaderShadernull-niivue/index.ts:443
bmpShaderShadernull-niivue/index.ts:430
bmpTextureWebGLTexturenull-niivue/index.ts:431
bmpTextureWHnumber1.0-niivue/index.ts:433
canvasHTMLCanvasElementnull-niivue/index.ts:376
circleShader?Shaderundefined-niivue/index.ts:428
clickToSegmentGrowingBitmapUint8Arraynull-niivue/index.ts:394
clickToSegmentIsGrowingbooleanfalse-niivue/index.ts:393
clickToSegmentXYnumber[]undefined-niivue/index.ts:395
CLIP_PLANE_IDnumber1-niivue/index.ts:543
colorbarHeightnumber0-niivue/index.ts:397
colorbarShader?Shaderundefined-niivue/index.ts:423
colormapListsColormapListEntry[][]-niivue/index.ts:381
colormapTextureWebGLTexturenull-niivue/index.ts:380
crosshairs3DNiivueObject3Dnull-niivue/index.ts:449
cuboidVertexBuffer?WebGLBufferundefined-niivue/index.ts:532
currentClipPlaneIndexnumber0-niivue/index.ts:539
currentDrawUndoBitmapnumberundefined-niivue/index.ts:884
customLayoutobject[][]-niivue/index.ts:555
customSliceShaderShadernull-niivue/index.ts:424
deferredMeshesLoadFromUrlParams[][]-niivue/index.ts:517
deferredVolumesImageFromUrlOptions[][]-niivue/index.ts:516
dicomLoaderDicomLoadernull-niivue/index.ts:367
DISTANCE_FROM_CAMERAnumber-0.54-niivue/index.ts:545
documentNVDocumentundefined-niivue/index.ts:843
dragModesobjectundefined-niivue/index.ts:621
dragModes.angleDRAG_MODEDRAG_MODE.angle-niivue/index.ts:624
dragModes.callbackOnlyDRAG_MODEDRAG_MODE.callbackOnly-niivue/index.ts:628
dragModes.contrastDRAG_MODEDRAG_MODE.contrast-niivue/index.ts:622
dragModes.measurementDRAG_MODEDRAG_MODE.measurement-niivue/index.ts:623
dragModes.noneDRAG_MODEDRAG_MODE.none-niivue/index.ts:625
dragModes.panDRAG_MODEDRAG_MODE.pan-niivue/index.ts:626
dragModes.slicer3DDRAG_MODEDRAG_MODE.slicer3D-niivue/index.ts:627
drawFillOverwritesbooleantrue-niivue/index.ts:400
drawLutLUTundefined-niivue/index.ts:390
drawOpacitynumber0.8-niivue/index.ts:391
drawPenAxCorSagnumber-1-niivue/index.ts:399
drawPenFillPtsnumber[][][]-niivue/index.ts:401
drawPenLocationnumber[]undefined-niivue/index.ts:398
drawRimOpacitynumber-1.0-niivue/index.ts:392
drawShapePreviewBitmapUint8Arraynull-niivue/index.ts:403
drawShapeStartLocationnumber[]undefined-niivue/index.ts:402
drawTextureWebGLTexturenull-niivue/index.ts:387
drawUndoBitmapsUint8Array[][]-niivue/index.ts:389
extentsMax?vec3undefined-niivue/index.ts:461
extentsMin?vec3undefined-niivue/index.ts:460
fiberShader?Shaderundefined-niivue/index.ts:426
fontShaderShadernull-niivue/index.ts:425
fontTextureWebGLTexturenull-niivue/index.ts:427
furthestFromPivotnumber10.0-niivue/index.ts:537
furthestVertexFromOriginnumber100-niivue/index.ts:518
genericVAOWebGLVertexArrayObjectnull-niivue/index.ts:447
gradientTextureWebGLTexturenull-niivue/index.ts:383
gradientTextureAmountnumber0.0-niivue/index.ts:384
graphGraphundefined-niivue/index.ts:546
growCutShader?Shaderundefined-niivue/index.ts:434
initializedbooleanfalse-niivue/index.ts:883
isBusybooleanfalse-niivue/index.ts:378
lastCallednumberundefined-niivue/index.ts:540
line3DShader?Shaderundefined-niivue/index.ts:415
lineShader?Shaderundefined-niivue/index.ts:414
loadersobject{}-niivue/index.ts:365
matCapTextureWebGLTexturenull-niivue/index.ts:429
mediaUrlMapMap< | NVMesh | NVImage, string>undefined-niivue/index.ts:882
meshShadersobject[]undefined-niivue/index.ts:561
mousePosnumber[]undefined-niivue/index.ts:521
needsRefreshbooleanfalse-niivue/index.ts:379
onAzimuthElevationChange(azimuth: number, elevation: number) => voidundefinedcallback function to run when the user changes the rotation of the 3D rendering Example niivue.onAzimuthElevationChange = (azimuth, elevation) => { console.log('azimuth: ', azimuth) console.log('elevation: ', elevation) }niivue/index.ts:806
onClickToSegment(data: object) => voidundefinedcallback function when clickToSegment is enabled and the user clicks on the image. data contains the volume of the segmented region in mm3 and mL Example niivue.onClickToSegment = (data) => { console.log('clicked to segment') console.log('volume mm3: ', data.mm3) console.log('volume mL: ', data.mL) }niivue/index.ts:687
onClipPlaneChange(clipPlane: number[]) => voidundefinedcallback function to run when the user changes the clip plane Example niivue.onClipPlaneChange = (clipPlane) => { console.log('clipPlane: ', clipPlane) }niivue/index.ts:815
onColormapChange() => voidundefined-niivue/index.ts:730
onCustomMeshShaderAdded(fragmentShaderText: string, name: string) => voidundefined-niivue/index.ts:816
onDebug() => voidundefinedcallback function to run when niivue reports a debug message Example niivue.onDebug = (debug) => { console.log('debug: ', debug) }niivue/index.ts:757
onDicomLoaderFinishedWithImages(files: | NVImage[] | NVMesh[]) => voidundefined-niivue/index.ts:820
onDocumentLoaded(document: NVDocument) => voidundefinedcallback function to run when the user loads a new NiiVue document Example niivue.onDocumentLoaded = (document) => { console.log('document: ', document) }niivue/index.ts:829
onDragRelease(params: DragReleaseParams) => voidundefinedcallback function to run when the right mouse button is released after dragging Example niivue.onDragRelease = () => { console.log('drag ended') }niivue/index.ts:646
onError() => voidundefinedcallback function to run when niivue reports an error Example niivue.onError = (error) => { console.log('error: ', error) }niivue/index.ts:727
onFrameChange(volume: NVImage, index: number) => voidundefinedcallback function to run when the user changes the volume when a 4D image is loaded Example niivue.onFrameChange = (volume, frameNumber) => { console.log('frame changed') console.log('volume: ', volume) console.log('frameNumber: ', frameNumber) }niivue/index.ts:718
onImageLoaded(volume: NVImage) => voidundefinedcallback function to run when a new volume is loaded Example niivue.onImageLoaded = (volume) => { console.log('volume loaded') console.log('volume: ', volume) }niivue/index.ts:697
onInfo() => voidundefinedcallback function to run when niivue reports detailed info Example niivue.onInfo = (info) => { console.log('info: ', info) }niivue/index.ts:739
onIntensityChange(volume: NVImage) => voidundefinedcallback function to run when the user changes the intensity range with the selection box action (right click) Example niivue.onIntensityChange = (volume) => { console.log('intensity changed') console.log('volume: ', volume) }niivue/index.ts:676
onLocationChange(location: unknown) => voidundefinedcallback function to run when the crosshair location changes Example niivue.onLocationChange = (data) => { console.log('location changed') console.log('mm: ', data.mm) console.log('vox: ', data.vox) console.log('frac: ', data.frac) console.log('values: ', data.values) }niivue/index.ts:667
onMeshAdded() => voidundefined-niivue/index.ts:792
onMeshAddedFromUrl(meshOptions: LoadFromUrlParams, mesh: NVMesh) => voidundefinedcallback function to run when a mesh is added from a url Example niivue.onMeshAddedFromUrl = (meshOptions, mesh) => { console.log('mesh added from url') console.log('meshOptions: ', meshOptions) console.log('mesh: ', mesh) }niivue/index.ts:789
onMeshLoaded(mesh: NVMesh) => voidundefinedcallback function to run when a new mesh is loaded Example niivue.onMeshLoaded = (mesh) => { console.log('mesh loaded') console.log('mesh: ', mesh) }niivue/index.ts:707
onMeshPropertyChanged(meshIndex: number, key: string, val: unknown) => voidundefined-niivue/index.ts:818
onMeshShaderChanged(meshIndex: number, shaderIndex: number) => voidundefined-niivue/index.ts:817
onMeshWithUrlRemoved(url: string) => voidundefined-niivue/index.ts:793
onMouseUp(data: Partial<UIData>) => voidundefinedcallback function to run when the left mouse button is released Example niivue.onMouseUp = () => { console.log('mouse up') }niivue/index.ts:655
onOptsChange(propertyName: keyof NVConfigOptions, newValue: | string | number | boolean | number[] | Float32Array | MouseEventConfig | TouchEventConfig | number[], oldValue: | string | number | boolean | number[] | Float32Array | MouseEventConfig | TouchEventConfig | number[]) => voidundefinedCallback for when any configuration option changes.niivue/index.ts:837
onVolumeAddedFromUrl(imageOptions: ImageFromUrlOptions, volume: NVImage) => voidundefinedcallback function to run when a volume is added from a url Example niivue.onVolumeAddedFromUrl = (imageOptions, volume) => { console.log('volume added from url') console.log('imageOptions: ', imageOptions) console.log('volume: ', volume) }niivue/index.ts:768
onVolumeUpdated() => voidundefinedcallback function to run when updateGLVolume is called (most users will not need to use Example niivue.onVolumeUpdated = () => { console.log('volume updated') }niivue/index.ts:778
onVolumeWithUrlRemoved(url: string) => voidundefined-niivue/index.ts:769
onWarn() => voidundefinedcallback function to run when niivue reports a warning Example niivue.onWarn = (warn) => { console.log('warn: ', warn) }niivue/index.ts:748
onZoom3DChange(zoom: number) => voidundefined-niivue/index.ts:796
orientCubeShader?Shaderundefined-niivue/index.ts:409
orientCubeShaderVAOWebGLVertexArrayObjectnull-niivue/index.ts:410
orientShaderAtlasIShadernull-niivue/index.ts:436
orientShaderAtlasUShadernull-niivue/index.ts:435
orientShaderFShadernull-niivue/index.ts:439
orientShaderIShadernull-niivue/index.ts:438
orientShaderPAQDShadernull-niivue/index.ts:441
orientShaderRGBUShadernull-niivue/index.ts:440
orientShaderUShadernull-niivue/index.ts:437
otherNVNiivue[]null-niivue/index.ts:534
overlayAlphaShadernumber1-niivue/index.ts:458
overlayOutlineWidthnumber0-niivue/index.ts:457
overlaysNVImage[][]-niivue/index.ts:515
overlayTextureWebGLTexturenull-niivue/index.ts:404
overlayTextureIDWebGLTexturenull-niivue/index.ts:405
paqdTextureWebGLTexturenull-niivue/index.ts:388
passThroughShader?Shaderundefined-niivue/index.ts:416
pickingImageShader?Shaderundefined-niivue/index.ts:422
pickingMeshShader?Shaderundefined-niivue/index.ts:421
pivot3Dnumber[]undefined-niivue/index.ts:536
position?vec3undefined-niivue/index.ts:459
readyForSyncbooleanfalse-niivue/index.ts:479
rectOutlineShader?Shaderundefined-niivue/index.ts:412
rectShader?Shaderundefined-niivue/index.ts:411
renderDrawAmbientOcclusionnumber0.4-niivue/index.ts:396
renderGradientShader?Shaderundefined-niivue/index.ts:417
renderGradientValuesbooleanfalse-niivue/index.ts:386
renderGradientValuesShader?Shaderundefined-niivue/index.ts:418
renderShader?Shaderundefined-niivue/index.ts:413
renderSliceShader?Shaderundefined-niivue/index.ts:419
renderVolumeShader?Shaderundefined-niivue/index.ts:420
screenSlicesobject[][]-niivue/index.ts:522
selectedObjectIdnumber-1-niivue/index.ts:542
slice2DShader?Shaderundefined-niivue/index.ts:407
sliceMMShader?Shaderundefined-niivue/index.ts:406
sliceTypeAxialSLICE_TYPESLICE_TYPE.AXIAL-niivue/index.ts:632
sliceTypeCoronalSLICE_TYPESLICE_TYPE.CORONAL-niivue/index.ts:633
sliceTypeMultiplanarSLICE_TYPESLICE_TYPE.MULTIPLANAR-niivue/index.ts:635
sliceTypeRenderSLICE_TYPESLICE_TYPE.RENDER-niivue/index.ts:636
sliceTypeSagittalSLICE_TYPESLICE_TYPE.SAGITTAL-niivue/index.ts:634
sliceV1Shader?Shaderundefined-niivue/index.ts:408
sobelBlurShaderShadernull-niivue/index.ts:444
sobelFirstOrderShaderShadernull-niivue/index.ts:445
sobelSecondOrderShaderShadernull-niivue/index.ts:446
surfaceShaderShadernull-niivue/index.ts:442
syncOptsSyncOptsundefined-niivue/index.ts:467
thumbnailVisiblebooleanfalse-niivue/index.ts:432
uiDataUIDataundefined-niivue/index.ts:482
unusedVAOanynull-niivue/index.ts:448
useCustomGradientTexturebooleanfalse-niivue/index.ts:385
volScalenumber[][]-niivue/index.ts:519
VOLUME_IDnumber254-niivue/index.ts:544
volumeObject3DNiivueObject3Dnull-niivue/index.ts:535
volumeTextureWebGLTexturenull-niivue/index.ts:382
voxnumber[][]-niivue/index.ts:520

Accessors

drawBitmap

Get Signature

get drawBitmap(): Uint8Array;

Defined in: niivue/index.ts:1000

Returns

Uint8Array

Set Signature

set drawBitmap(drawBitmap: Uint8Array): void;

Defined in: niivue/index.ts:1004

Parameters
ParameterType
drawBitmapUint8Array
Returns

void


isAlphaClipDark

Get Signature

get isAlphaClipDark(): boolean;

Defined in: niivue/index.ts:869

Get whether voxels below minimum intensity are drawn as dark or transparent.

Returns

boolean

True if dark voxels are opaque, false if transparent.

Set Signature

set isAlphaClipDark(newVal: boolean): void;

Defined in: niivue/index.ts:878

Set whether voxels below minimum intensity are drawn as dark or transparent.

See

live demo usage

Parameters
ParameterTypeDescription
newValbooleanTrue to make dark voxels opaque, false for transparent.
Returns

void


meshes

Get Signature

get meshes(): NVMesh[];

Defined in: niivue/index.ts:992

Returns

NVMesh[]

Set Signature

set meshes(meshes: NVMesh[]): void;

Defined in: niivue/index.ts:996

Parameters
ParameterType
meshesNVMesh[]
Returns

void


opts

Get Signature

get opts(): NVConfigOptions;

Defined in: niivue/index.ts:851

Get the current visualization options.

Returns

NVConfigOptions


scene

Get Signature

get scene(): Scene;

Defined in: niivue/index.ts:846

Get the current scene configuration.

Returns

Scene


sliceMosaicString

Get Signature

get sliceMosaicString(): string;

Defined in: niivue/index.ts:856

Get the slice mosaic layout string.

Returns

string

Set Signature

set sliceMosaicString(newSliceMosaicString: string): void;

Defined in: niivue/index.ts:861

Set the slice mosaic layout string.

Parameters
ParameterType
newSliceMosaicStringstring
Returns

void


volScaleMultiplier

Get Signature

get volScaleMultiplier(): number;

Defined in: niivue/index.ts:1008

Returns

number

Set Signature

set volScaleMultiplier(scale: number): void;

Defined in: niivue/index.ts:1012

Parameters
ParameterType
scalenumber
Returns

void


volumes

Get Signature

get volumes(): NVImage[];

Defined in: niivue/index.ts:984

Returns

NVImage[]

Set Signature

set volumes(volumes: NVImage[]): void;

Defined in: niivue/index.ts:988

Parameters
ParameterType
volumesNVImage[]
Returns

void

Methods

addColormap()

addColormap(key: string, cmap: ColorMap): void;

Defined in: niivue/index.ts:8769

create a new colormap

Parameters

ParameterTypeDescription
keystringname of new colormap
cmapColorMapcolormap properties (Red, Green, Blue, Alpha and Indices)

Returns

void

See

live demo usage


addLabel()

addLabel(
text: string,
style: NVLabel3DStyle,
points?: number[] | number[][],
anchor?: LabelAnchorPoint,
onClick?: (label: NVLabel3D) => void): NVLabel3D;

Defined in: niivue/index.ts:12995

Add a 3D Label

Parameters

ParameterTypeDescription
textstringthe text content of the label
styleNVLabel3DStylevisual styling options for the label (e.g., color, scale, line width)
points?number[] | number[][]a 3D point [x, y, z] or array of points to anchor the label in space
anchor?LabelAnchorPointoptional label anchor position (e.g., top-left, center, etc.)
onClick?(label: NVLabel3D) => voidoptional callback function to invoke when the label is clicked

Returns

NVLabel3D

the created NVLabel3D instance

See

live demo usage


addMesh()

addMesh(mesh: NVMesh): void;

Defined in: niivue/index.ts:3504

add a new mesh to the canvas

Parameters

ParameterTypeDescription
meshNVMeshthe new mesh to add to the canvas

Returns

void

Example

niivue = new Niivue();
niivue.addMesh(NVMesh.loadFromUrl({ url: "../someURL.gii" }));

See

live demo usage


addMeshesFromUrl()

addMeshesFromUrl(meshOptions: LoadFromUrlParams[]): Promise<NVMesh[]>;

Defined in: niivue/index.ts:5331

Add mesh and notify subscribers

Parameters

ParameterType
meshOptionsLoadFromUrlParams[]

Returns

Promise<NVMesh[]>


addMeshFromUrl()

addMeshFromUrl(meshOptions: LoadFromUrlParams): Promise<NVMesh>;

Defined in: niivue/index.ts:5310

Add mesh and notify subscribers

Parameters

ParameterType
meshOptionsLoadFromUrlParams

Returns

Promise<NVMesh>


addVolume()

addVolume(volume: NVImage): void;

Defined in: niivue/index.ts:3487

add a new volume to the canvas

Parameters

ParameterTypeDescription
volumeNVImagethe new volume to add to the canvas

Returns

void

Example

niivue = new Niivue();
niivue.addVolume(NVImage.loadFromUrl({ url: "../someURL.nii.gz" }));

See

live demo usage


addVolumeFromUrl()

addVolumeFromUrl(imageOptions: ImageFromUrlOptions): Promise<NVImage>;

Defined in: niivue/index.ts:2699

Add an image and notify subscribers

Parameters

ParameterType
imageOptionsImageFromUrlOptions

Returns

Promise<NVImage>

See

live demo usage


addVolumesFromUrl()

addVolumesFromUrl(imageOptionsArray: ImageFromUrlOptions[]): Promise<NVImage[]>;

Defined in: niivue/index.ts:2711

Parameters

ParameterType
imageOptionsArrayImageFromUrlOptions[]

Returns

Promise<NVImage[]>


attachTo()

attachTo(id: string, isAntiAlias: any): Promise<Niivue>;

Defined in: niivue/index.ts:1060

attach the Niivue instance to the webgl2 canvas by element id

Parameters

ParameterTypeDefault valueDescription
idstringundefinedthe id of an html canvas element
isAntiAliasanynulldetermines if anti-aliasing is requested (if not specified, AA usage depends on hardware)

Returns

Promise<Niivue>

Examples

niivue = new Niivue().attachTo("gl");
await niivue.attachTo("gl");

See

live demo usage


attachToCanvas()

attachToCanvas(canvas: HTMLCanvasElement, isAntiAlias: boolean): Promise<Niivue>;

Defined in: niivue/index.ts:1074

attach the Niivue instance to a canvas element directly

Parameters

ParameterTypeDefault valueDescription
canvasHTMLCanvasElementundefinedthe canvas element reference
isAntiAliasbooleannull-

Returns

Promise<Niivue>

Example

niivue = new Niivue();
await niivue.attachToCanvas(document.getElementById(id));

See

live demo usage


binarize()

binarize(volume: NVImage): void;

Defined in: niivue/index.ts:3687

Binarize a volume by converting all non-zero voxels to 1

Parameters

ParameterTypeDescription
volumeNVImagethe image volume to modify in place

Returns

void

See

live demo usage


broadcastTo()

broadcastTo(otherNV: Niivue | Niivue[], syncOpts: object): void;

Defined in: niivue/index.ts:1167

Sync the scene controls (orientation, crosshair location, etc.) from one Niivue instance to others. useful for using one canvas to drive another.

Parameters

ParameterTypeDescription
otherNVNiivue | Niivue[]the other Niivue instance(s)
syncOpts{ 2d: boolean; 3d: boolean; }-
syncOpts.2dboolean-
syncOpts.3dboolean-

Returns

void

Example

niivue1 = new Niivue();
niivue2 = new Niivue();
niivue3 = new Niivue();
niivue1.broadcastTo(niivue2);
niivue1.broadcastTo([niivue2, niivue3]);

See

live demo usage


cleanup()

cleanup(): void;

Defined in: niivue/index.ts:932

Clean up event listeners and observers Call this when the Niivue instance is no longer needed. This will be called when the canvas is detached from the DOM

Returns

void

Example

niivue.cleanup();

clearAllMeasurements()

clearAllMeasurements(): void;

Defined in: niivue/index.ts:10839

Clear all persistent measurements and angles from the canvas.

Returns

void

Example

nv.clearAllMeasurements();

clearAngles()

clearAngles(): void;

Defined in: niivue/index.ts:10827

Clear all persistent angle measurements from the canvas.

Returns

void

Example

nv.clearAngles();

clearCustomLayout()

clearCustomLayout(): void;

Defined in: niivue/index.ts:3323

Clear custom layout and rely on built-in layouts

Returns

void


clearMeasurements()

clearMeasurements(): void;

Defined in: niivue/index.ts:10815

Clear all persistent measurement lines from the canvas.

Returns

void

Example

nv.clearMeasurements();

cloneVolume()

cloneVolume(index: number): NVImage;

Defined in: niivue/index.ts:4833

clone a volume and return a new volume

Parameters

ParameterTypeDescription
indexnumberthe index of the volume to clone

Returns

NVImage

new volume to work with, but that volume is not added to the canvas

Example

niivue = new Niivue();
niivue.cloneVolume(0);

closeDrawing()

closeDrawing(): void;

Defined in: niivue/index.ts:6674

close drawing: make sure you have saved any changes before calling this!

Returns

void

Example

niivue.closeDrawing();

See

live demo usage


colormap()

colormap(lutName: string, isInvert: boolean): Uint8ClampedArray;

Defined in: niivue/index.ts:9693

Retrieve a colormap with optional inversion

Parameters

ParameterTypeDefault valueDescription
lutNamestring''name of the lookup table (LUT) colormap
isInvertbooleanfalsewhether to invert the colormap

Returns

Uint8ClampedArray

the RGBA colormap as a Uint8ClampedArray

See

live demo usage


colormaps()

colormaps(): string[];

Defined in: niivue/index.ts:8759

query all available color maps that can be applied to volumes

Returns

string[]

an array of colormap strings

Example

niivue = new Niivue();
colormaps = niivue.colormaps();

See

live demo usage


conform()

conform(
volume: NVImage,
toRAS: boolean,
isLinear: boolean,
asFloat32: boolean,
isRobustMinMax: boolean): Promise<NVImage>;

Defined in: niivue/index.ts:9396

FreeSurfer-style conform reslices any image to a 256x256x256 volume with 1mm voxels

Parameters

ParameterTypeDefault valueDescription
volumeNVImageundefinedinput volume to be re-oriented, intensity-scaled and resliced
toRASbooleanfalsereslice to row, column slices to right-anterior-superior not left-inferior-anterior (default false).
isLinearbooleantruereslice with linear rather than nearest-neighbor interpolation (default true).
asFloat32booleanfalseuse Float32 datatype rather than Uint8 (default false).
isRobustMinMaxbooleanfalseclamp intensity with robust min max (~2%..98%) instead of FreeSurfer (0%..99.99%) (default false).

Returns

Promise<NVImage>

See

live demo usage


createConnectedLabelImage()

createConnectedLabelImage(
id: string,
conn: number,
binarize: boolean,
onlyLargestClusterPerClass: boolean): Promise<NVImage>;

Defined in: niivue/index.ts:9108

Create a connected component label map from a volume

Parameters

ParameterTypeDefault valueDescription
idstringundefinedID of the input volume
connnumber26connectivity for clustering (6 = faces, 18 = faces + edges, 26 = faces + edges + corners)
binarizebooleanfalsewhether to binarize the volume before labeling
onlyLargestClusterPerClassbooleanfalseretain only the largest cluster for each label

Returns

Promise<NVImage>

a new NVImage with labeled clusters, using random colormap

See

live demo usage


createCustomMeshShader()

createCustomMeshShader(fragmentShaderText: string, name: string): object;

Defined in: niivue/index.ts:7252

Parameters

ParameterTypeDefault valueDescription
fragmentShaderTextstringundefinedcustom fragment shader.
namestring'Custom'title for new shader.

Returns

object

created custom mesh shader

NameTypeDefined in
Fragstringniivue/index.ts:7256
Namestringniivue/index.ts:7256
shaderShaderniivue/index.ts:7256

createEmptyDrawing()

createEmptyDrawing(): void;

Defined in: niivue/index.ts:5529

generate a blank canvas for the pen tool

Returns

void

Example

niivue.createEmptyDrawing();

See

live demo usage


createNiftiArray()

createNiftiArray(
dims: number[],
pixDims: number[],
affine: number[],
datatypeCode: NiiDataType,
img: Uint8Array): Promise<Uint8Array>;

Defined in: niivue/index.ts:9352

Create a binary NIfTI file as a Uint8Array, including header and image data

Parameters

ParameterTypeDefault valueDescription
dimsnumber[]...image dimensions [x, y, z]
pixDimsnumber[]...voxel dimensions in mm [x, y, z]
affinenumber[]...4×4 affine transformation matrix in row-major order
datatypeCodeNiiDataTypeNiiDataType.DT_UINT8NIfTI datatype code (e.g., DT_UINT8, DT_FLOAT32)
imgUint8Array...image data buffer (optional)

Returns

Promise<Uint8Array>

a Uint8Array representing a complete NIfTI file

See

live demo usage


createOnLocationChange()

createOnLocationChange(axCorSag: number): void;

Defined in: niivue/index.ts:12872

Internal utility to generate human-readable location strings for the onLocationChange callback

Parameters

ParameterTypeDefault valueDescription
axCorSagnumberNaNoptional axis index for coordinate interpretation (NaN by default)

Returns

void

Remarks

Computes string representation of current crosshair position in mm (and frame if 4D).

See

live demo usage


decimateHierarchicalMesh()

decimateHierarchicalMesh(mesh: number, order: number): boolean;

Defined in: niivue/index.ts:4107

reduce complexity of FreeSurfer mesh

Parameters

ParameterTypeDefault valueDescription
meshnumberundefinedidentity of mesh to change
ordernumber3decimation order 0..6

Returns

boolean

boolean false if mesh is not hierarchical or of lower order

Example

niivue.decimateHierarchicalMesh(niivue.meshes[0].id, 4);

See

live demo usage


doSyncGamma()

doSyncGamma(otherNV: Niivue): void;

Defined in: niivue/index.ts:1196

Parameters

ParameterType
otherNVNiivue

Returns

void


drawGrowCut()

drawGrowCut(): void;

Defined in: niivue/index.ts:5595

dilate drawing so all voxels are colored. works on drawing with multiple colors

Returns

void

Example

niivue.drawGrowCut();

See

live demo usage


drawingBinaryDilationWithSeed()

drawingBinaryDilationWithSeed(seedXYZ: number[], neighbors: 6 | 18 | 26): void;

Defined in: niivue/index.ts:5927

Performs a 1-voxel binary dilation on a connected cluster within the drawing mask using the drawFloodFillCore function.

Parameters

ParameterTypeDefault valueDescription
seedXYZnumber[]undefinedvoxel index of the seed voxel in the mask array.
neighbors6 | 18 | 266Number of neighbors to consider for connectivity and dilation (6, 18, or 26).

Returns

void


drawMosaic()

drawMosaic(mosaicStr: string): void;

Defined in: niivue/index.ts:14447

display a lightbox or montage view

Parameters

ParameterTypeDescription
mosaicStrstringspecifies orientation (A,C,S) and location of slices.

Returns

void

Example

niivue.setSliceMosaicString("A -10 0 20");

See

live demo usage


drawOtsu()

drawOtsu(levels: number): void;

Defined in: niivue/index.ts:3846

remove dark voxels in air

Parameters

ParameterTypeDefault valueDescription
levelsnumber2(2-4) segment brain into this many types. For example drawOtsu(2) will create a binary drawing where bright voxels are colored and dark voxels are clear.

Returns

void

Example

niivue.drawOtsu(3);

See

live demo usage


drawUndo()

drawUndo(): void;

Defined in: niivue/index.ts:3567

Restore drawing to previous state

Returns

void

Example

niivue.drawUndo();

See

live demo usage


findDrawingBoundarySlices()

findDrawingBoundarySlices(sliceType: SLICE_TYPE): object;

Defined in: niivue/index.ts:15274

Find the first and last slices containing drawing data along a given axis

Parameters

ParameterTypeDescription
sliceTypeSLICE_TYPEThe slice orientation (AXIAL, CORONAL, or SAGITTAL)

Returns

object

Object containing first and last slice indices, or null if no data found

NameTypeDefined in
firstnumberniivue/index.ts:15274
lastnumberniivue/index.ts:15274

frac2canvasPos()

frac2canvasPos(frac: vec3): number[];

Defined in: niivue/index.ts:13921

Parameters

ParameterType
fracvec3

Returns

number[]


generateHTML()

generateHTML(canvasId: string, esm: string): Promise<string>;

Defined in: niivue/index.ts:5028

generates HTML of current scene

Parameters

ParameterTypeDefault valueDescription
canvasIdstring'gl1'id of canvas NiiVue will be attached to
esmstringundefinedbundled version of NiiVue

Returns

Promise<string>

HTML with javascript of the current scene

Example

const template = `<html><body><canvas id="gl1"></canvas><script type="module" async>
%%javascript%%</script></body></html>`;
nv1.generateHTML("page.html", esm);

generateLoadDocumentJavaScript()

generateLoadDocumentJavaScript(canvasId: string, esm: string): Promise<string>;

Defined in: niivue/index.ts:4987

generates JavaScript to load the current scene as a document

Parameters

ParameterTypeDescription
canvasIdstringid of canvas NiiVue will be attached to
esmstringbundled version of NiiVue

Returns

Promise<string>

Example

const javascript = this.generateLoadDocumentJavaScript("gl1");
const html = `<html><body><canvas id="gl1"></canvas><script type="module" async>
${javascript}</script></body></html>`;

See

live demo usage


getCustomLayout()

getCustomLayout(): object[];

Defined in: niivue/index.ts:3332

Get the current custom layout if set

Returns

object[]

The current custom layout or null if using built-in layouts


getDescriptives()

getDescriptives(options: object): Descriptive;

Defined in: niivue/index.ts:7868

basic statistics for selected voxel-based image

Parameters

ParameterTypeDescription
options{ drawingIsMask?: boolean; endVox?: number[]; layer?: number; masks?: number[]; roiIsMask?: boolean; startVox?: number[]; }an object containing the following properties: - layer: selects image to describe - masks: optional binary images to filter voxels - drawingIsMask: a boolean indicating if the drawing is used as a mask - roiIsMask: a boolean indicating if the ROI is used as a mask - startVox: the starting voxel coordinates - endVox: the ending voxel coordinates
options.drawingIsMask?boolean-
options.endVox?number[]-
options.layer?number-
options.masks?number[]-
options.roiIsMask?boolean-
options.startVox?number[]-

Returns

Descriptive

numeric values to describe image or regions of images

Example

niivue.getDescriptives({
layer: 0,
masks: [],
drawingIsMask: true, // drawingIsMask and roiIsMask are mutually exclusive
roiIsMask: false,
startVox: [10, 20, 30], // ignored if roiIsMask is false
endVox: [40, 50, 60], // ignored if roiIsMask is false
});

See

live demo usage


getDicomLoader()

getDicomLoader(): DicomLoader;

Defined in: niivue/index.ts:2981

Get the currently assigned DICOM loader.

Returns

DicomLoader


getFrame4D()

getFrame4D(id: string): number;

Defined in: niivue/index.ts:9673

determine active 3D volume from 4D time series

Parameters

ParameterTypeDescription
idstringthe ID of the 4D NVImage

Returns

number

currently selected volume (indexed from 0)

Example

nv1.getFrame4D(nv1.volumes[0].id);

See

live demo usage


getGradientTextureData()

getGradientTextureData(): Float32Array;

Defined in: niivue/index.ts:7649

Get the gradient texture produced by gradientGL as a TypedArray

Returns

Float32Array

Float32Array containing the gradient texture data, or null if no gradient texture exists

Example

niivue = new Niivue();
niivue.loadVolumes([{ url: "./someImage.nii" }]);
// ... after volume is loaded and gradient is computed
const gradientData = niivue.getGradientTextureData();
if (gradientData) {
console.log("Gradient texture dimensions:", gradientData.length);
}

See

live demo usage


getMeshIndexByID()

getMeshIndexByID(id: string | number): number;

Defined in: niivue/index.ts:4040

Returns the index of a mesh given its ID or index.

Parameters

ParameterTypeDescription
idstring | numberThe mesh ID as a string, or an index number.

Returns

number

The mesh index, or -1 if not found or out of range.


getMouseEventConfig()

getMouseEventConfig(): MouseEventConfig;

Defined in: niivue/index.ts:10936

Get current mouse event configuration.

Returns

MouseEventConfig

Current mouse event configuration or undefined if using defaults


getOverlayIndexByID()

getOverlayIndexByID(id: string): number;

Defined in: niivue/index.ts:4186

get the index of an overlay by its unique id. unique ids are assigned to the NVImage.id property when a new NVImage is created.

Parameters

ParameterTypeDescription
idstringthe id string to search for

Returns

number

See

NiiVue#getVolumeIndexByID

Example

niivue = new Niivue();
niivue.getOverlayIndexByID(someVolume.id);

getRadiologicalConvention()

getRadiologicalConvention(): boolean;

Defined in: niivue/index.ts:3430

Detect if display is using radiological or neurological convention.

Returns

boolean

radiological convention status

Example

let rc = niivue.getRadiologicalConvention();

getTouchEventConfig()

getTouchEventConfig(): TouchEventConfig;

Defined in: niivue/index.ts:10944

Get current touch event configuration.

Returns

TouchEventConfig

Current touch event configuration or undefined if using defaults


getVolumeIndexByID()

getVolumeIndexByID(id: string): number;

Defined in: niivue/index.ts:3518

get the index of a volume by its unique id. unique ids are assigned to the NVImage.id property when a new NVImage is created.

Parameters

ParameterTypeDescription
idstringthe id string to search for

Returns

number

Example

niivue = new Niivue();
niivue.getVolumeIndexByID(someVolume.id);

indexNearestXYZmm()

indexNearestXYZmm(
mesh: number,
Xmm: number,
Ymm: number,
Zmm: number): number[];

Defined in: niivue/index.ts:4090

returns the index of the mesh vertex that is closest to the provided coordinates

Parameters

ParameterTypeDescription
meshnumberidentity of mesh to change
Xmmnumberlocation in left/right dimension
Ymmnumberlocation in posterior/anterior dimension
Zmmnumberlocation in foot/head dimension

Returns

number[]

the an array where ret[0] is the mesh index and ret[1] is distance from vertex to coordinates

Example

niivue.indexNearestXYZmm(niivue.meshes[0].id, -22, 42, 13);

See

live demo usage


interpolateMaskSlices()

interpolateMaskSlices(
sliceIndexLow?: number,
sliceIndexHigh?: number,
options?: object): void;

Defined in: niivue/index.ts:15289

Interpolate between mask slices using geometric or intensity-guided methods

Parameters

ParameterTypeDescription
sliceIndexLow?numberLower slice index (optional, will auto-detect if not provided)
sliceIndexHigh?numberHigher slice index (optional, will auto-detect if not provided)
options?{ applySmoothingToSlices?: boolean; binaryThreshold?: number; intensitySigma?: number; intensityWeight?: number; sliceType?: SLICE_TYPE; useIntensityGuided?: boolean; }Interpolation options
options.applySmoothingToSlices?boolean-
options.binaryThreshold?number-
options.intensitySigma?number-
options.intensityWeight?number-
options.sliceType?SLICE_TYPE-
options.useIntensityGuided?boolean-

Returns

void


json()

json(): ExportDocumentData;

Defined in: niivue/index.ts:5118

Converts NiiVue scene to JSON

Returns

ExportDocumentData


loadConnectome()

loadConnectome(json:
| Connectome
| LegacyConnectome): this;

Defined in: niivue/index.ts:5512

load a connectome specified by json

Parameters

ParameterTypeDescription
json| Connectome | LegacyConnectomeconnectome model

Returns

this

Niivue instance

See

live demo usage


loadConnectomeFromUrl()

loadConnectomeFromUrl(url: string, headers: object): Promise<Niivue>;

Defined in: niivue/index.ts:5429

Load a connectome from a given URL and initialize it.

Parameters

ParameterTypeDescription
urlstringthe URL to a JSON-formatted connectome definition
headers{ }optional HTTP headers to include with the request (e.g. for authorization)

Returns

Promise<Niivue>

the Niivue instance (for method chaining)

See

live demo usage


loadDeferred4DVolumes()

loadDeferred4DVolumes(id: string): Promise<void>;

Defined in: niivue/index.ts:9614

Load all volumes for image opened with limitFrames4D, the user can also click the ... on a 4D timeline to load deferred volumes

Parameters

ParameterTypeDescription
idstringthe ID of the 4D NVImage

Returns

Promise<void>


loadDicoms()

loadDicoms(dicomList: ImageFromUrlOptions[]): Promise<Niivue>;

Defined in: niivue/index.ts:5214

Parameters

ParameterType
dicomListImageFromUrlOptions[]

Returns

Promise<Niivue>


loadDocument()

loadDocument(document: NVDocument): Promise<Niivue>;

Defined in: niivue/index.ts:4850

Loads an NVDocument

Parameters

ParameterType
documentNVDocument

Returns

Promise<Niivue>

Niivue instance

See

live demo usage


loadDocumentFromUrl()

loadDocumentFromUrl(url: string): Promise<void>;

Defined in: niivue/index.ts:4840

Loads an NVDocument from a URL and integrates it into the scene.

Parameters

ParameterType
urlstring

Returns

Promise<void>


loadDrawing()

loadDrawing(drawingBitmap: NVImage): boolean;

Defined in: niivue/index.ts:3586

Loads a drawing overlay and aligns it with the current background image. Converts the input image to match the background's orientation and stores it as a drawable bitmap. Initializes the undo history and prepares the drawing texture.

Parameters

ParameterTypeDescription
drawingBitmapNVImageA NVImage object representing the drawing to load. Must match the dimensions of the background image.

Returns

boolean

true if the drawing was successfully loaded and aligned; false if dimensions are incompatible.


loadDrawingFromUrl()

loadDrawingFromUrl(fnm: string, isBinarize: boolean): Promise<boolean>;

Defined in: niivue/index.ts:3709

Open drawing

Parameters

ParameterTypeDefault valueDescription
fnmstringundefinedfilename of NIfTI format drawing
isBinarizebooleanfalseif true will force drawing voxels to be either 0 or 1.

Returns

Promise<boolean>

Example

niivue.loadDrawingFromUrl("../images/lesion.nii.gz");

See

live demo usage


loadFont()

loadFont(fontSheetUrl: any, metricsUrl: object): Promise<void>;

Defined in: niivue/index.ts:7151

Load typeface for colorbars, measurements and orientation text.

Parameters

ParameterTypeDefault valueDescription
fontSheetUrlanydefaultFontPNGURL to a bitmap font sheet image (e.g., a PNG atlas of glyphs)
metricsUrl{ atlas: { distanceRange: number; height: number; size: number; type: string; width: number; yOrigin: string; }; glyphs: ( | { advance: number; atlasBounds?: undefined; planeBounds?: undefined; unicode: number; } | { advance: number; atlasBounds: { bottom: number; left: number; right: number; top: number; }; planeBounds: { bottom: number; left: number; right: number; top: number; }; unicode: number; })[]; kerning: any[]; metrics: { ascender: number; descender: number; emSize: number; lineHeight: number; underlineThickness: number; underlineY: number; }; }defaultFontMetricsURL to the corresponding font metrics JSON (defines character bounds and spacing)
metricsUrl.atlas{ distanceRange: number; height: number; size: number; type: string; width: number; yOrigin: string; }...-
metricsUrl.atlas.distanceRangenumber2-
metricsUrl.atlas.heightnumber256-
metricsUrl.atlas.sizenumber59.65625-
metricsUrl.atlas.typestring"msdf"-
metricsUrl.atlas.widthnumber512-
metricsUrl.atlas.yOriginstring"bottom"-
metricsUrl.glyphs( | { advance: number; atlasBounds?: undefined; planeBounds?: undefined; unicode: number; } | { advance: number; atlasBounds: { bottom: number; left: number; right: number; top: number; }; planeBounds: { bottom: number; left: number; right: number; top: number; }; unicode: number; })[]...-
metricsUrl.kerningany[][]-
metricsUrl.metrics{ ascender: number; descender: number; emSize: number; lineHeight: number; underlineThickness: number; underlineY: number; }...-
metricsUrl.metrics.ascendernumber0.927734375-
metricsUrl.metrics.descendernumber-0.244140625-
metricsUrl.metrics.emSizenumber1-
metricsUrl.metrics.lineHeightnumber1.171875-
metricsUrl.metrics.underlineThicknessnumber0.048828125-
metricsUrl.metrics.underlineYnumber-0.09765625-

Returns

Promise<void>

a Promise that resolves when the font is loaded

Example

niivue.loadFont("./Roboto.png", "./Roboto.json");

See

live demo usage


loadFreeSurferConnectome()

loadFreeSurferConnectome(json: FreeSurferConnectome): Promise<Niivue>;

Defined in: niivue/index.ts:5454

load a connectome specified by json

Parameters

ParameterTypeDescription
jsonFreeSurferConnectomefreesurfer model

Returns

Promise<Niivue>

Niivue instance

See

live demo usage


loadFreeSurferConnectomeFromUrl()

loadFreeSurferConnectomeFromUrl(url: string, headers: object): Promise<Niivue>;

Defined in: niivue/index.ts:5442

Load a FreeSurfer-style connectome from a given URL and initialize it.

Parameters

ParameterTypeDescription
urlstringthe URL of the JSON-formatted connectome file
headers{ }optional HTTP headers to include in the fetch request (e.g. for authorization)

Returns

Promise<Niivue>

the Niivue instance (for method chaining)

See

live demo usage


loadFromArrayBuffer()

loadFromArrayBuffer(buffer: ArrayBuffer, name: string): Promise<void>;

Defined in: niivue/index.ts:2899

Load an image or mesh from an array buffer

Parameters

ParameterTypeDescription
bufferArrayBufferArrayBuffer with the entire contents of a mesh or volume
namestringstring of filename, extension used to infer type (NIfTI, MGH, MZ3, etc)

Returns

Promise<void>

See

live demo usage


loadFromFile()

loadFromFile(file: File): Promise<void>;

Defined in: niivue/index.ts:2917

Load a mesh or image volume from a File object

Parameters

ParameterTypeDescription
fileFileFile object selected by the user (e.g. from an HTML input element)

Returns

Promise<void>

a Promise that resolves when the file has been loaded and added to the scene

See

live demo usage


loadFromUrl()

loadFromUrl(fnm: string): Promise<NVImage>;

Defined in: niivue/index.ts:9377

Load a NIfTI image from a URL and convert it to an NVImage object

Parameters

ParameterTypeDescription
fnmstringURL of the NIfTI file to load

Returns

Promise<NVImage>

a Promise resolving to an NVImage (not yet added to GPU or scene)

See

live demo usage


loadImages()

loadImages(images: (
| ImageFromUrlOptions
| LoadFromUrlParams)[]): Promise<Niivue>;

Defined in: niivue/index.ts:5175

Load an array of image or mesh URLs using appropriate handlers

Parameters

ParameterTypeDescription
images( | ImageFromUrlOptions | LoadFromUrlParams)[]array of image or mesh descriptors (with URL and optional name)

Returns

Promise<Niivue>

a Promise resolving to the current NiiVue instance after loading completes

Remarks

Automatically dispatches each item to either volume or mesh loader based on file extension or registered custom loader

See

live demo usage


loadMatCapTexture()

loadMatCapTexture(bmpUrl: string): Promise<WebGLTexture>;

Defined in: niivue/index.ts:7094

Load matcap for illumination model.

Parameters

ParameterTypeDescription
bmpUrlstringname of matcap to load ("Shiny", "Cortex", "Cream")

Returns

Promise<WebGLTexture>

Example

niivue.loadMatCapTexture("Cortex");

See

live demo usage


loadMeshes()

loadMeshes(meshList: LoadFromUrlParams[]): Promise<Niivue>;

Defined in: niivue/index.ts:5391

load an array of meshes

Parameters

ParameterTypeDescription
meshListLoadFromUrlParams[]the array of objects to load. each object must have a resolvable "url" property at a minimum

Returns

Promise<Niivue>

Niivue instance

Example

niivue = new Niivue();
niivue.loadMeshes([{ url: "someMesh.gii" }]);

See

live demo usage


loadVolumes()

loadVolumes(volumeList: ImageFromUrlOptions[]): Promise<Niivue>;

Defined in: niivue/index.ts:5264

load an array of volume objects

Parameters

ParameterTypeDescription
volumeListImageFromUrlOptions[]the array of objects to load. each object must have a resolvable "url" property at a minimum

Returns

Promise<Niivue>

returns the Niivue instance

Example

niivue = new Niivue()
niivue.loadVolumes([{url: 'someImage.nii.gz}, {url: 'anotherImage.nii.gz'}])

See

live demo usage


meshShaderNames()

meshShaderNames(sort: boolean): string[];

Defined in: niivue/index.ts:7335

retrieve all currently loaded meshes

Parameters

ParameterTypeDefault valueDescription
sortbooleantruesort output alphabetically

Returns

string[]

list of available mesh shader names

Example

niivue.meshShaderNames();

See

live demo usage


moveCrosshairInVox()

moveCrosshairInVox(
x: number,
y: number,
z: number): void;

Defined in: niivue/index.ts:13723

move crosshair a fixed number of voxels (not mm)

Parameters

ParameterTypeDescription
xnumbertranslate left (-) or right (+)
ynumbertranslate posterior (-) or +anterior (+)
znumbertranslate inferior (-) or superior (+)

Returns

void

Example

niivue.moveCrosshairInVox(1, 0, 0);

See

live demo usage


moveVolumeDown()

moveVolumeDown(volume: NVImage): void;

Defined in: niivue/index.ts:4367

Move a volume down one index position in the stack of loaded volumes. This moves it down one layer

Parameters

ParameterTypeDescription
volumeNVImagethe volume to move

Returns

void

Example

niivue = new Niivue();
niivue.moveVolumeDown(this.volumes[1]); // move the second image to the background position (it was 1 index, now will be 0)

moveVolumeToBottom()

moveVolumeToBottom(volume: NVImage): void;

Defined in: niivue/index.ts:4344

Move a volume to the bottom of the stack of loaded volumes. The volume will become the background

Parameters

ParameterTypeDescription
volumeNVImagethe volume to move

Returns

void

Example

niivue = new Niivue();
niivue.moveVolumeToBottom(this.volumes[3]); // move the 4th volume to the 0 position. It will be the new background

moveVolumeToTop()

moveVolumeToTop(volume: NVImage): void;

Defined in: niivue/index.ts:4379

Move a volume to the top position in the stack of loaded volumes. This will be the top layer

Parameters

ParameterTypeDescription
volumeNVImagethe volume to move

Returns

void

Example

niivue = new Niivue();
niivue.moveVolumeToTop(this.volumes[0]); // move the background image to the top layer position

moveVolumeUp()

moveVolumeUp(volume: NVImage): void;

Defined in: niivue/index.ts:4355

Move a volume up one index position in the stack of loaded volumes. This moves it up one layer

Parameters

ParameterTypeDescription
volumeNVImagethe volume to move

Returns

void

Example

niivue = new Niivue();
niivue.moveVolumeUp(this.volumes[0]); // move the background image to the second index position (it was 0 index, now will be 1)

niftiArray2NVImage()

niftiArray2NVImage(bytes: Uint8Array): Promise<NVImage>;

Defined in: niivue/index.ts:9367

Convert a binary NIfTI file (as a Uint8Array) to an NVImage object

Parameters

ParameterTypeDescription
bytesUint8Arraybinary contents of a NIfTI file

Returns

Promise<NVImage>

a Promise resolving to an NVImage object

See

live demo usage


refreshColormaps()

refreshColormaps(): Niivue;

Defined in: niivue/index.ts:9748

Rebuild and upload all colormap textures for volumes and meshes

Returns

Niivue

the current NiiVue instance, or undefined if no colormaps are used

See

live demo usage


refreshDrawing()

refreshDrawing(isForceRedraw: boolean, useClickToSegmentBitmap: boolean): void;

Defined in: niivue/index.ts:6688

copy drawing bitmap from CPU to GPU storage and redraw the screen

Parameters

ParameterTypeDefault valueDescription
isForceRedrawbooleantruerefreshes scene immediately (default true)
useClickToSegmentBitmapbooleanfalse-

Returns

void

Example

niivue.refreshDrawing();

See

live demo usage


removeHaze()

removeHaze(level: number, volIndex: number): void;

Defined in: niivue/index.ts:3886

remove dark voxels in air

Parameters

ParameterTypeDefault valueDescription
levelnumber5(1-5) larger values for more preserved voxels
volIndexnumber0volume to dehaze

Returns

void

Example

niivue.removeHaze(3, 0);

See

live demo usage


removeMesh()

removeMesh(mesh: NVMesh): void;

Defined in: niivue/index.ts:4312

Remove a triangulated mesh, connectome or tractogram

Parameters

ParameterTypeDescription
meshNVMeshmesh to delete

Returns

void

Example

niivue = new Niivue();
niivue.removeMesh(this.meshes[3]);

See

live demo usage


removeMeshByUrl()

removeMeshByUrl(url: string): void;

Defined in: niivue/index.ts:4328

Remove a triangulated mesh, connectome or tractogram

Parameters

ParameterTypeDescription
urlstringURL of mesh to delete

Returns

void

Example

niivue.removeMeshByUrl("../images/cit168.mz3");

removeVolume()

removeVolume(volume: NVImage): void;

Defined in: niivue/index.ts:4277

Remove a volume

Parameters

ParameterTypeDescription
volumeNVImagevolume to delete

Returns

void

Example

niivue = new Niivue();
niivue.removeVolume(this.volumes[3]);

See

live demo usage


removeVolumeByIndex()

removeVolumeByIndex(index: number): void;

Defined in: niivue/index.ts:4297

Remove a volume from the scene by its index

Parameters

ParameterTypeDescription
indexnumberindex of the volume to remove

Returns

void

Throws

if the index is out of bounds

See

live demo usage


removeVolumeByUrl()

removeVolumeByUrl(url: string): void;

Defined in: niivue/index.ts:2794

Remove volume by url

Parameters

ParameterTypeDescription
urlstringVolume added by url to remove

Returns

void

See

live demo usage


reverseFaces()

reverseFaces(mesh: number): void;

Defined in: niivue/index.ts:4124

reverse triangle winding of mesh (swap front and back faces)

Parameters

ParameterTypeDescription
meshnumberidentity of mesh to change

Returns

void

Example

niivue.reverseFaces(niivue.meshes[0].id);

See

live demo usage


saveDocument()

saveDocument(
fileName: string,
compress: boolean,
options: object): Promise<void>;

Defined in: niivue/index.ts:5145

Save the current scene as an .nvd document.

Parameters

ParameterTypeDefault valueDescription
fileNamestring'untitled.nvd'Name of the file to create (default "untitled.nvd")
compressbooleantrueIf true, gzip-compress the JSON (default true)
options{ embedImages?: boolean; embedPreview?: boolean; }{}Fine-grained switches: • embedImages – store encodedImageBlobs (default true) • embedPreview – store previewImageDataURL (default true)
options.embedImages?booleanundefined-
options.embedPreview?booleanundefined-

Returns

Promise<void>

Example

// smallest possible file – no preview, just metadata
await nv.saveDocument("scene.nvd", true, {
embedImages: false,
embedPreview: false,
});

See

live demo usage


saveHTML()

saveHTML(
fileName: string,
canvasId: string,
esm: string): Promise<void>;

Defined in: niivue/index.ts:5110

Save the current scene as a standalone HTML file

Parameters

ParameterTypeDefault valueDescription
fileNamestring'untitled.html'name of the HTML file to save (default: "untitled.html")
canvasIdstring'gl1'ID of the canvas element NiiVue will attach to
esmstringundefinedbundled ES module source for NiiVue

Returns

Promise<void>

a Promise that resolves when the file is downloaded

See

live demo usage


saveImage()

saveImage(options: SaveImageOptions): Promise<boolean | Uint8Array>;

Defined in: niivue/index.ts:3937

Save voxel-based image to disk.

Parameters

ParameterTypeDefault valueDescription
optionsSaveImageOptionsdefaultSaveImageOptionsconfiguration object with the following fields: - filename: name of the NIfTI image to create - isSaveDrawing: whether to save the drawing layer or the background image - volumeByIndex: which image layer to save (0 for background)

Returns

Promise<boolean | Uint8Array>

true if successful when writing to disk, or a Uint8Array if exported as binary data

Example

niivue.saveImage({ filename: "myimage.nii.gz", isSaveDrawing: true });
niivue.saveImage({ filename: "myimage.nii.gz", isSaveDrawing: true });

See

live demo usage


saveScene()

saveScene(filename: string): Promise<void>;

Defined in: niivue/index.ts:1022

save webgl2 canvas as png format bitmap

Parameters

ParameterTypeDefault valueDescription
filenamestring'niivue.png'filename for screen capture

Returns

Promise<void>

Example

niivue.saveScene("test.png");

See

live demo usage


setAdditiveBlend()

setAdditiveBlend(isAdditiveBlend: boolean): void;

Defined in: niivue/index.ts:3420

control whether voxel overlays are combined using additive (emission) or traditional (transmission) blending.

Parameters

ParameterTypeDescription
isAdditiveBlendbooleanemission (true) or transmission (false) mixing

Returns

void

Example

niivue.isAdditiveBlend(true);

See

live demo usage


setAtlasOutline()

setAtlasOutline(isOutline: number): void;

Defined in: niivue/index.ts:11626

Enable or disable atlas outline overlay

Parameters

ParameterTypeDescription
isOutlinenumbernumber 0 to 1 for outline opacity

Returns

void

See

live demo usage


setClipPlane()

setClipPlane(depthAzimuthElevation: number[]): void;

Defined in: niivue/index.ts:4456

Update the clip plane orientation in 3D view mode.

Parameters

ParameterTypeDescription
depthAzimuthElevationnumber[]a 3-component array: - depth: distance of clip plane from center of volume (0 to ~1.73, or >2.0 to disable clipping) - azimuth: camera angle around the object in degrees (0–360 or -180–180) - elevation: camera height in degrees (-90 to 90)

Returns

void

Example

niivue = new Niivue();
niivue.setClipPlane([42, 42]);

See

live demo usage


setClipPlaneColor()

setClipPlaneColor(color: number[]): void;

Defined in: niivue/index.ts:4677

set the color of the 3D clip plane

Parameters

ParameterTypeDescription
colornumber[]the new color. expects an array of RGBA values. values can range from 0 to 1

Returns

void

Example

niivue.setClipPlaneColor([1, 1, 1, 0.5]); // white, transparent

See

live demo usage


setClipPlaneThick()

setClipPlaneThick(thick: number): void;

Defined in: niivue/index.ts:4691

adjust thickness of the 3D clip plane

Parameters

ParameterTypeDescription
thicknumberthickness of slab. Value 0..1.73 (cube opposite corner length is sqrt(3)).

Returns

void

Example

niivue.setClipPlaneThick(0.3); // thin slab

See

live demo usage


setClipVolume()

setClipVolume(low: number[], high: number[]): void;

Defined in: niivue/index.ts:4708

set the clipping region for volume rendering

Parameters

ParameterTypeDescription
lownumber[]3-component array specifying the lower bound of the clipping region along the X, Y, and Z axes. Values range from 0 (start) to 1 (end of volume).
highnumber[]3-component array specifying the upper bound of the clipping region along the X, Y, and Z axes. Values range from 0 to 1.

Returns

void

Example

niivue.setClipPlaneColor([0.0, 0.0, 0.2], [1.0, 1.0, 0.7]); // remove inferior 20% and superior 30%

See

live demo usage


setColormap()

setColormap(id: string, colormap: string): void;

Defined in: niivue/index.ts:8781

update the colormap of an image given its ID

Parameters

ParameterTypeDescription
idstringthe ID of the NVImage
colormapstringthe name of the colormap to use

Returns

void

Example

niivue.setColormap(niivue.volumes[0].id,, 'red')

See

live demo usage


setColorMap()

setColorMap(id: string, colormap: string): void;

Defined in: niivue/index.ts:9555

Parameters

ParameterTypeDescription
idstringID of the volume
colormapstringname of the colormap to apply

Returns

void

Deprecated

Use setColormap instead. This alias is retained for compatibility with NiiVue < 0.35.


setColormapNegative()

setColormapNegative(id: string, colormapNegative: string): void;

Defined in: niivue/index.ts:9568

use given color map for negative voxels in image

Parameters

ParameterTypeDescription
idstringthe ID of the NVImage
colormapNegativestringthe name of the colormap to use

Returns

void

Example

niivue = new Niivue();
niivue.setColormapNegative(niivue.volumes[1].id, "winter");

See

live demo usage


setCornerOrientationText()

setCornerOrientationText(isCornerOrientationText: boolean): void;

Defined in: niivue/index.ts:3225

determine if text appears at corner (true) or sides of 2D slice.

Parameters

ParameterTypeDescription
isCornerOrientationTextbooleancontrols position of text

Returns

void

Example

niivue.setCornerOrientationText(true);

See

live demo usage


setCrosshairColor()

setCrosshairColor(color: number[]): void;

Defined in: niivue/index.ts:4478

set the crosshair and colorbar outline color

Parameters

ParameterTypeDescription
colornumber[]an RGBA array. values range from 0 to 1

Returns

void

Example

niivue = new Niivue();
niivue.setCrosshairColor([0, 1, 0, 0.5]); // set crosshair to transparent green

See

live demo usage


setCrosshairWidth()

setCrosshairWidth(crosshairWidth: number): void;

Defined in: niivue/index.ts:4488

set thickness of crosshair

Parameters

ParameterType
crosshairWidthnumber

Returns

void

Example

niivue.crosshairWidth(2);

See

live demo usage


setCustomGradientTexture()

setCustomGradientTexture(data: Float32Array | Uint8Array, dims?: number[]): void;

Defined in: niivue/index.ts:7738

Set a custom gradient texture to use instead of the one produced by gradientGL When a custom gradient texture is set, the useCustomGradientTexture flag is set to true to prevent gradientGL from overwriting the custom texture during volume updates.

Parameters

ParameterTypeDescription
dataFloat32Array | Uint8ArrayFloat32Array or Uint8Array containing RGBA gradient data, or null to revert to auto-generated gradient
dims?number[]Optional dimensions array [width, height, depth]. If not provided, uses current volume dimensions

Returns

void

Example

niivue = new Niivue();
niivue.loadVolumes([{ url: "./someImage.nii" }]);
// Create custom gradient data
const customGradient = new Float32Array(256 * 256 * 256 * 4); // example dimensions
// ... fill customGradient with desired values
niivue.setCustomGradientTexture(customGradient, [256, 256, 256]);

// To revert to auto-generated gradient:
niivue.setCustomGradientTexture(null);

See

live demo usage


setCustomLayout()

setCustomLayout(layout: object[]): void;

Defined in: niivue/index.ts:3288

Set a custom slice layout. This overrides the built-in layouts.

Parameters

ParameterTypeDescription
layoutobject[]Array of layout specifications for each slice view

Returns

void

Example

niivue.setCustomLayout([
// Left 50% - Sag
{sliceType: 2, position: [0, 0, 0.5, 1.0]},
// Top right - Cor
{sliceType: 1, position: [0.5, 0, 0.5, 0.5]},
// Bottom right - Ax
{sliceType: 0, position: [0.5, 0.5, 0.5, 0.5]}
])

produces:
+----------------+----------------+
| | |
| | coronal |
| | |
| | |
| sagittal +----------------+
| | |
| | axial |
| | |
| | |
+----------------+----------------+

setCustomMeshShader()

setCustomMeshShader(fragmentShaderText: string, name: string): number;

Defined in: niivue/index.ts:7320

Define a new GLSL shader program to influence mesh coloration

Parameters

ParameterTypeDefault valueDescription
fragmentShaderTextstring''the GLSL source code for the custom fragment shader
namestring'Custom'a descriptive label for the shader (used in menus or debugging)

Returns

number

the index of the new shader (use with setMeshShader)

See

live demo usage


setDefaults()

setDefaults(options: Partial<NVConfigOptions>, resetBriCon: boolean): void;

Defined in: niivue/index.ts:3358

Reset scene to default settings.

Parameters

ParameterTypeDefault valueDescription
optionsPartial<NVConfigOptions>{}
resetBriConbooleanfalsealso reset contrast (default false).

Returns

void

See

Example

niivue.nv1.setDefaults(opts, true);

setDragMode()

setDragMode(mode: string | DRAG_MODE): void;

Defined in: niivue/index.ts:10849

Set the drag mode for mouse interactions.

Parameters

ParameterTypeDescription
modestring | DRAG_MODEThe drag mode to set ('none', 'contrast', 'measurement', 'angle', 'pan', 'slicer3D', 'callbackOnly', 'roiSelection')

Returns

void


setDrawColormap()

setDrawColormap(name: string): void;

Defined in: niivue/index.ts:4510

Parameters

ParameterType
namestring

Returns

void


setDrawingEnabled()

setDrawingEnabled(trueOrFalse: boolean): void;

Defined in: niivue/index.ts:4521

does dragging over a 2D slice create a drawing?

Parameters

ParameterTypeDescription
trueOrFalsebooleanenabled (true) or not (false)

Returns

void

Example

niivue.setDrawingEnabled(true);

See

live demo usage


setDrawOpacity()

setDrawOpacity(opacity: number): void;

Defined in: niivue/index.ts:4567

control whether drawing is transparent (0), opaque (1) or translucent (between 0 and 1).

Parameters

ParameterTypeDescription
opacitynumbertranslucency of drawing

Returns

void

Example

niivue.setDrawOpacity(0.7);

See

live demo usage


setFrame4D()

setFrame4D(id: string, frame4D: number): void;

Defined in: niivue/index.ts:9646

show desired 3D volume from 4D time series

Parameters

ParameterTypeDescription
idstringthe ID of the 4D NVImage
frame4Dnumberframe to display (indexed from zero)

Returns

void

Example

nv1.setFrame4D(nv1.volumes[0].id, 42);

See

live demo usage


setGamma()

setGamma(gamma: number): void;

Defined in: niivue/index.ts:9605

adjust screen gamma. Low values emphasize shadows but can appear flat, high gamma hides shadow details.

Parameters

ParameterTypeDefault valueDescription
gammanumber1.0selects luminance, default is 1

Returns

void

Example

niivue.setGamma(1.0);

See

live demo usage


setGradientOpacity()

setGradientOpacity(gradientOpacity: number, renderSilhouette: number): Promise<void>;

Defined in: niivue/index.ts:4764

set volume rendering opacity influence of the gradient magnitude

Parameters

ParameterTypeDefault valueDescription
gradientOpacitynumber0.0amount of gradient magnitude influence on opacity (0..1), default 0 (no-influence)
renderSilhouettenumber0.0make core transparent to enhance rims (0..1), default 0 (no-influence)

Returns

Promise<void>

Example

niivue.setGradientOpacity(0.6);

See

live demo usage


setHeroImage()

setHeroImage(fraction: number): void;

Defined in: niivue/index.ts:3257

determine proportion of screen real estate devoted to rendering in multiplanar view.

Parameters

ParameterTypeDescription
fractionnumberproportion of screen devoted to primary (hero) image (0 to disable)

Returns

void

Example

niivue.setHeroImage(0.5);

See

live demo usage


setHighResolutionCapable()

setHighResolutionCapable(forceDevicePixelRatio: number | boolean): void;

Defined in: niivue/index.ts:3440

Force WebGL canvas to use high resolution display, regardless of browser defaults.

Parameters

ParameterTypeDescription
forceDevicePixelRationumber | boolean1: block high DPI; 0= allow high DPI: >0 use specified pixel ratio

Returns

void

Example

niivue.setHighResolutionCapable(true);

See

live demo usage


setInterpolation()

setInterpolation(isNearest: boolean): void;

Defined in: niivue/index.ts:11638

select between nearest and linear interpolation for voxel based images

Parameters

ParameterTypeDescription
isNearestbooleanwhether nearest neighbor interpolation is used, else linear interpolation

Returns

void

Example

niivue.setInterpolation(true);

See

live demo usage


setIsOrientationTextVisible()

setIsOrientationTextVisible(isOrientationTextVisible: boolean): void;

Defined in: niivue/index.ts:3236

Show or hide orientation labels (e.g., L/R, A/P) in 2D slice views

Parameters

ParameterTypeDescription
isOrientationTextVisiblebooleanwhether orientation text should be displayed

Returns

void

Example

niivue.setIsOrientationTextVisible(false);

See

live demo usage


setMesh()

setMesh(mesh: NVMesh, toIndex: number): void;

Defined in: niivue/index.ts:4245

Reorders a mesh within the internal mesh list.

Parameters

ParameterTypeDefault valueDescription
meshNVMeshundefinedThe NVMesh instance to reposition.
toIndexnumber0Target index to move the mesh to. - If 0, moves mesh to the front. - If < 0, removes the mesh. - If within bounds, inserts mesh at the specified index.

Returns

void


setMeshLayerProperty()

setMeshLayerProperty(
mesh: number,
layer: number,
key: keyof NVMeshLayer,
val: number): Promise<void>;

Defined in: niivue/index.ts:4143

reverse triangle winding of mesh (swap front and back faces)

Parameters

ParameterTypeDescription
meshnumberidentity of mesh to change
layernumberselects the mesh overlay (e.g. GIfTI or STC file)
keykeyof NVMeshLayerattribute to change
valnumbervalue for attribute

Returns

Promise<void>

Example

niivue.setMeshLayerProperty(niivue.meshes[0].id, 0, "frame4D", 22);

See

live demo usage


setMeshProperty()

setMeshProperty(
id: number,
key: keyof NVMesh,
val:
| string
| number
| boolean
| number[]
| ColorMap
| Float32Array
| Uint8Array
| LegacyConnectome): void;

Defined in: niivue/index.ts:4065

change property of mesh, tractogram or connectome

Parameters

ParameterTypeDescription
idnumberidentity of mesh to change
keykeyof NVMeshattribute to change
val| string | number | boolean | number[] | ColorMap | Float32Array | Uint8Array | LegacyConnectomefor attribute

Returns

void

Example

niivue.setMeshProperty(niivue.meshes[0].id, "fiberLength", 42);

See

live demo usage


setMeshShader()

setMeshShader(id: number, meshShaderNameOrNumber: number): void;

Defined in: niivue/index.ts:7222

select new shader for triangulated meshes and connectomes. Note that this function requires the mesh is fully loaded: you may want use await with loadMeshes (as seen in live demo).

Parameters

ParameterTypeDefault valueDescription
idnumberundefinedid of mesh to change
meshShaderNameOrNumbernumber2identify shader for usage

Returns

void

Example

niivue.setMeshShader("toon");

See

live demo usage


setMeshThicknessOn2D()

setMeshThicknessOn2D(meshThicknessOn2D: number): void;

Defined in: niivue/index.ts:3387

Limit visibility of mesh in front of a 2D image. Requires world-space mode.

Parameters

ParameterTypeDescription
meshThicknessOn2Dnumberdistance from voxels for clipping mesh. Use Infinity to show entire mesh or 0.0 to hide mesh.

Returns

void

Example

niivue.setMeshThicknessOn2D(42);

See

live demo usage


setModulationImage()

setModulationImage(
idTarget: string,
idModulation: string,
modulateAlpha: number): void;

Defined in: niivue/index.ts:9583

modulate intensity of one image based on intensity of another

Parameters

ParameterTypeDefault valueDescription
idTargetstringundefinedthe ID of the NVImage to be biased
idModulationstringundefinedthe ID of the NVImage that controls bias (empty string to disable modulation)
modulateAlphanumber0does the modulation influence alpha transparency (values greater than 1).

Returns

void

Example

niivue.setModulationImage(niivue.volumes[0].id, niivue.volumes[1].id);

See


setMouseEventConfig()

setMouseEventConfig(config: MouseEventConfig): void;

Defined in: niivue/index.ts:10909

Set custom mouse event configuration for button mappings.

Parameters

ParameterTypeDescription
configMouseEventConfigMouse event configuration object

Returns

void

Example

nv.setMouseEventConfig({
leftButton: {
primary: DRAG_MODE.windowing,
withShift: DRAG_MODE.measurement,
withCtrl: DRAG_MODE.crosshair,
},
rightButton: DRAG_MODE.crosshair,
centerButton: DRAG_MODE.pan,
});

setMultiplanarLayout()

setMultiplanarLayout(layout: number): void;

Defined in: niivue/index.ts:3211

control placement of 2D slices.

Parameters

ParameterTypeDescription
layoutnumberAUTO: 0, COLUMN: 1, GRID: 2, ROW: 3,

Returns

void

Example

niivue.setMultiplanarLayout(2);

See

live demo usage


setMultiplanarPadPixels()

setMultiplanarPadPixels(pixels: number): void;

Defined in: niivue/index.ts:3200

insert a gap between slices of a mutliplanar view.

Parameters

ParameterTypeDescription
pixelsnumberspacing between tiles of multiplanar view

Returns

void

Example

niivue.setMultiplanarPadPixels(4);

See

live demo usage


setOpacity()

setOpacity(volIdx: number, newOpacity: number): void;

Defined in: niivue/index.ts:4653

set the opacity of a volume given by volume index

Parameters

ParameterTypeDescription
volIdxnumberthe volume index of the volume to change
newOpacitynumberthe opacity value. valid values range from 0 to 1. 0 will effectively remove a volume from the scene

Returns

void

Example

niivue = new Niivue();
niivue.setOpacity(0, 0.5); // make the first volume transparent

See

live demo usage


setPan2Dxyzmm()

setPan2Dxyzmm(xyzmmZoom: vec4): void;

Defined in: niivue/index.ts:4158

adjust offset position and scale of 2D sliceScale

Parameters

ParameterTypeDescription
xyzmmZoomvec4first three components are spatial, fourth is scaling

Returns

void

Example

niivue.setPan2Dxyzmm([5, -4, 2, 1.5]);

setPenValue()

setPenValue(penValue: number, isFilledPen: boolean): void;

Defined in: niivue/index.ts:4555

determine color and style of drawing

Parameters

ParameterTypeDefault valueDescription
penValuenumberundefinedsets the color of the pen
isFilledPenbooleanfalsedetermines if dragging creates flood-filled shape

Returns

void

Example

niivue.setPenValue(1, true);

See

live demo usage


setRadiologicalConvention()

setRadiologicalConvention(isRadiologicalConvention: boolean): void;

Defined in: niivue/index.ts:3346

control whether 2D slices use radiological or neurological convention.

Parameters

ParameterTypeDescription
isRadiologicalConventionbooleannew display convention

Returns

void

Example

niivue.setRadiologicalConvention(true);

See

live demo usage


setRenderAzimuthElevation()

setRenderAzimuthElevation(a: number, e: number): void;

Defined in: niivue/index.ts:4171

set rotation of 3D render view

Parameters

ParameterType
anumber
enumber

Returns

void

Example

niivue.setRenderAzimuthElevation(45, 15);

See

live demo usage


setRenderDrawAmbientOcclusion()

setRenderDrawAmbientOcclusion(ao: number): void;

Defined in: niivue/index.ts:9539

darken crevices and brighten corners when 3D rendering drawings.

Parameters

ParameterTypeDescription
aonumberamount of ambient occlusion (default 0.4)

Returns

void

See

live demo usage


setScale()

setScale(scale: number): void;

Defined in: niivue/index.ts:4665

set the scale of the 3D rendering. Larger numbers effectively zoom.

Parameters

ParameterTypeDescription
scalenumberthe new scale value

Returns

void

Example

niivue.setScale(2); // zoom some

See

live demo usage


setSelectionBoxColor()

setSelectionBoxColor(color: number[]): void;

Defined in: niivue/index.ts:4580

set the selection box color. A selection box is drawn when you right click and drag to change image contrast

Parameters

ParameterTypeDescription
colornumber[]an RGBA array. values range from 0 to 1

Returns

void

Example

niivue = new Niivue();
niivue.setSelectionBoxColor([0, 1, 0, 0.5]); // set to transparent green

See

live demo usage


setShowAllOrientationMarkers()

setShowAllOrientationMarkers(showAllOrientationMarkers: boolean): void;

Defined in: niivue/index.ts:3246

Show or hide all four orientation labels (e.g., L/R, A/P, S/I) in 2D slice views

Parameters

ParameterTypeDescription
showAllOrientationMarkersbooleanwhether all four orientation markers should be displayed

Returns

void

Example

niivue.setShowAllOrientationMarkers(true);

setSliceMM()

setSliceMM(isSliceMM: boolean): void;

Defined in: niivue/index.ts:3409

control 2D slice view mode.

Parameters

ParameterTypeDescription
isSliceMMbooleancontrol whether 2D slices use world space (true) or voxel space (false). Beware that voxel space mode limits properties like panning, zooming and mesh visibility.

Returns

void

Example

niivue.setSliceMM(true);

See

live demo usage


setSliceMosaicString()

setSliceMosaicString(str: string): void;

Defined in: niivue/index.ts:3398

Create a custom multi-slice mosaic (aka lightbox, montage) view.

Parameters

ParameterTypeDescription
strstringdescription of mosaic.

Returns

void

Example

niivue.setSliceMosaicString("A 0 20 C 30 S 42");

See

live demo usage


setSliceType()

setSliceType(st: SLICE_TYPE): this;

Defined in: niivue/index.ts:4638

set the slice type. This changes the view mode

Parameters

ParameterTypeDescription
stSLICE_TYPEsliceType is an enum of slice types to use

Returns

this

Example

niivue = new Niivue();
niivue.setSliceType(Niivue.sliceTypeMultiplanar);

See

live demo usage


setTouchEventConfig()

setTouchEventConfig(config: TouchEventConfig): void;

Defined in: niivue/index.ts:10926

Set custom touch event configuration for touch gesture mappings.

Parameters

ParameterTypeDescription
configTouchEventConfigTouch event configuration object

Returns

void

Example

nv.setTouchEventConfig({
singleTouch: DRAG_MODE.windowing,
doubleTouch: DRAG_MODE.pan,
});

setVolume()

setVolume(volume: NVImage, toIndex: number): void;

Defined in: niivue/index.ts:4205

set the index of a volume. This will change it's ordering and appearance if there are multiple volumes loaded.

Parameters

ParameterTypeDefault valueDescription
volumeNVImageundefinedthe volume to update
toIndexnumber0the index to move the volume to. The default is the background (0 index)

Returns

void

Example

niivue = new Niivue();
niivue.setVolume(someVolume, 1); // move it to the second position in the array of loaded volumes (0 is the first position)

setVolumeRenderIllumination()

setVolumeRenderIllumination(gradientAmount: number): Promise<void>;

Defined in: niivue/index.ts:4728

set proportion of volume rendering influenced by selected matcap.

Parameters

ParameterTypeDefault valueDescription
gradientAmountnumber0.0amount of matcap (NaN or 0..1), default 0 (matte, surface normal does not influence color). NaN renders the gradients.

Returns

Promise<void>

Example

niivue.setVolumeRenderIllumination(0.6);

See


sph2cartDeg()

sph2cartDeg(azimuth: number, elevation: number): number[];

Defined in: niivue/index.ts:4428

convert spherical AZIMUTH, ELEVATION to Cartesian

Parameters

ParameterTypeDescription
azimuthnumberazimuth number
elevationnumberelevation number

Returns

number[]

the converted [x, y, z] coordinates

Example

niivue = new Niivue();
xyz = niivue.sph2cartDeg(42, 42);

syncWith()

syncWith(otherNV: Niivue | Niivue[], syncOpts: object): void;

Defined in: niivue/index.ts:1147

Sync the scene controls (orientation, crosshair location, etc.) from one Niivue instance to another. useful for using one canvas to drive another.

Parameters

ParameterTypeDescription
otherNVNiivue | Niivue[]the other Niivue instance that is the main controller
syncOpts{ 2d: boolean; 3d: boolean; }-
syncOpts.2dboolean-
syncOpts.3dboolean-

Returns

void

Example

niivue1 = new Niivue();
niivue2 = new Niivue();
niivue2.syncWith(niivue1);

Deprecated

use broadcastTo instead

See

live demo usage


unwatchOptsChanges()

unwatchOptsChanges(): void;

Defined in: niivue/index.ts:3475

Stop watching for changes to configuration options. This removes the current onOptsChange callback.

Returns

void

Example

niivue.unwatchOptsChanges();

See

live demo usage


updateGLVolume()

updateGLVolume(): void;

Defined in: niivue/index.ts:7815

update the webGL 2.0 scene after making changes to the array of volumes. It's always good to call this method after altering one or more volumes manually (outside of Niivue setter methods)

Returns

void

Example

niivue = new Niivue();
niivue.updateGLVolume();

See

live demo usage


useDicomLoader()

useDicomLoader(loader: DicomLoader): void;

Defined in: niivue/index.ts:2974

Set a custom loader for handling DICOM files.

Parameters

ParameterType
loaderDicomLoader

Returns

void


useLoader()

useLoader(
loader: unknown,
fileExt: string,
toExt: string): void;

Defined in: niivue/index.ts:2961

Registers a custom external file loader for handling specific file types in Niivue.

This method allows you to define how certain file extensions are handled when loaded into Niivue. The provided loader function should return an object containing an ArrayBuffer of the file's contents and the file extension (used for inferring how Niivue should process the data).

Optionally, positions and indices can be returned to support loading mesh data (e.g. .mz3 format).

Parameters

ParameterTypeDescription
loaderunknownA function that accepts a File or ArrayBuffer and returns an object with arrayBuffer and fileExt properties. May also return positions and indices for meshes.
fileExtstringThe original file extension (e.g. 'iwi.cbor') to associate with this loader.
toExtstringThe target file extension Niivue should treat the file as (e.g. 'nii' or 'mz3').

Returns

void

Example

const myCustomLoader = async (file) => {
const arrayBuffer = await file.arrayBuffer()
return {
arrayBuffer,
fileExt: 'iwi.cbor',
positions: new Float32Array(...),
indices: new Uint32Array(...)
}
}

nv.useLoader(myCustomLoader, 'iwi.cbor', 'nii')

watchOptsChanges()

watchOptsChanges(callback: (propertyName: keyof NVConfigOptions, newValue:
| string
| number
| boolean
| number[]
| Float32Array
| MouseEventConfig
| TouchEventConfig
| number[], oldValue:
| string
| number
| boolean
| number[]
| Float32Array
| MouseEventConfig
| TouchEventConfig
| number[]) => void): void;

Defined in: niivue/index.ts:3459

Start watching for changes to configuration options. This is a convenience method that sets up the onOptsChange callback.

Parameters

ParameterTypeDescription
callback(propertyName: keyof NVConfigOptions, newValue: | string | number | boolean | number[] | Float32Array | MouseEventConfig | TouchEventConfig | number[], oldValue: | string | number | boolean | number[] | Float32Array | MouseEventConfig | TouchEventConfig | number[]) => voidFunction to call when any option changes

Returns

void

Example

niivue.watchOptsChanges((propertyName, newValue, oldValue) => {
console.log(`Option ${propertyName} changed from ${oldValue} to ${newValue}`);
});

See

live demo usage