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.

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

Constructors

Properties

Methods

addColormap addLabel addMesh addMeshesFromUrl addMeshFromUrl addVolume addVolumeFromUrl arrayEquals attachTo attachToCanvas broadcastTo calculateMinMaxVoxIdx cloneVolume closeDrawing colormaps conform createCustomMeshShader createEmptyDrawing decimateHierarchicalMesh drawGrowCut drawingBinaryDilationWithSeed drawMosaic drawOtsu drawUndo generateHTML generateLoadDocumentJavaScript getDescriptives getFrame4D getMediaByUrl getOverlayIndexByID getRadiologicalConvention getVolumeIndexByID indexNearestXYZmm isMeshExt json loadConnectome loadConnectomeFromUrl loadDeferred4DVolumes loadDocument loadDocumentFromUrl loadDrawingFromUrl loadFont loadFreeSurferConnectome loadFreeSurferConnectomeFromUrl loadFromArrayBuffer loadFromFile loadMatCapTexture loadMeshes loadVolumes meshShaderNames moveCrosshairInVox moveVolumeDown moveVolumeToBottom moveVolumeToTop moveVolumeUp refreshDrawing removeHaze removeMesh removeMeshByUrl removeVolume removeVolumeByIndex removeVolumeByUrl reverseFaces saveDocument saveHTML saveImage saveScene setAdditiveBlend setClipPlane setClipPlaneColor setClipPlaneThick setClipVolume setColormap setColormapNegative setCornerOrientationText setCrosshairColor setCrosshairWidth setCustomMeshShader setDefaults setDrawingEnabled setDrawOpacity setFrame4D setGamma setHeroImage setHighResolutionCapable setInterpolation setMeshLayerProperty setMeshProperty setMeshShader setMeshThicknessOn2D setModulationImage setMultiplanarLayout setMultiplanarPadPixels setOpacity setPan2Dxyzmm setPenValue setRadiologicalConvention setRenderAzimuthElevation setRenderDrawAmbientOcclusion setScale setSelectionBoxColor setSliceMM setSliceMosaicString setSliceType setVolume setVolumeRenderIllumination sph2cartDeg syncWith updateGLVolume

Constructors

Properties

onAzimuthElevationChange: ((azimuth: number, elevation: number) => void) = ...

callback function to run when the user changes the rotation of the 3D rendering

niivue.onAzimuthElevationChange = (azimuth, elevation) => {
console.log('azimuth: ', azimuth)
console.log('elevation: ', elevation)
}
onClickToSegment: ((data: {
    mL: number;
    mm3: number;
}) => void) = ...

callback function when clickToSegment is enabled and the user clicks on the image. data contains the volume of the segmented region in mm3 and mL

niivue.onClickToSegment = (data) => {
console.log('clicked to segment')
console.log('volume mm3: ', data.mm3)
console.log('volume mL: ', data.mL)
}
onClipPlaneChange: ((clipPlane: number[]) => void) = ...

callback function to run when the user changes the clip plane

niivue.onClipPlaneChange = (clipPlane) => {
console.log('clipPlane: ', clipPlane)
}
onDebug: (() => void) = ...

callback function to run when niivue reports a debug message

niivue.onDebug = (debug) => {
console.log('debug: ', debug)
}
onDocumentLoaded: ((document: NVDocument) => void) = ...

callback function to run when the user loads a new NiiVue document

niivue.onDocumentLoaded = (document) => {
console.log('document: ', document)
}
onDragRelease: ((params: DragReleaseParams) => void) = ...

callback function to run when the right mouse button is released after dragging

niivue.onDragRelease = () => {
console.log('drag ended')
}
onError: (() => void) = ...

callback function to run when niivue reports an error

niivue.onError = (error) => {
console.log('error: ', error)
}
onFrameChange: ((volume: NVImage, index: number) => void) = ...

callback function to run when the user changes the volume when a 4D image is loaded

niivue.onFrameChange = (volume, frameNumber) => {
console.log('frame changed')
console.log('volume: ', volume)
console.log('frameNumber: ', frameNumber)
}
onImageLoaded: ((volume: NVImage) => void) = ...

callback function to run when a new volume is loaded

niivue.onImageLoaded = (volume) => {
console.log('volume loaded')
console.log('volume: ', volume)
}
onInfo: (() => void) = ...

callback function to run when niivue reports detailed info

niivue.onInfo = (info) => {
console.log('info: ', info)
}
onIntensityChange: ((volume: NVImage) => void) = ...

callback function to run when the user changes the intensity range with the selection box action (right click)

niivue.onIntensityChange = (volume) => {
console.log('intensity changed')
console.log('volume: ', volume)
}
onLocationChange: ((location: unknown) => void) = ...

callback function to run when the crosshair location changes

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)
}
onMeshAddedFromUrl: ((meshOptions: LoadFromUrlParams, mesh: NVMesh) => void) = ...

callback function to run when a mesh is added from a url

niivue.onMeshAddedFromUrl = (meshOptions, mesh) => {
console.log('mesh added from url')
console.log('meshOptions: ', meshOptions)
console.log('mesh: ', mesh)
}
onMeshLoaded: ((mesh: NVMesh) => void) = ...

callback function to run when a new mesh is loaded

niivue.onMeshLoaded = (mesh) => {
console.log('mesh loaded')
console.log('mesh: ', mesh)
}
onMouseUp: ((data: Partial<UIData>) => void) = ...

callback function to run when the left mouse button is released

niivue.onMouseUp = () => {
console.log('mouse up')
}
onVolumeAddedFromUrl: ((imageOptions: ImageFromUrlOptions, volume: NVImage) => void) = ...

callback function to run when a volume is added from a url

niivue.onVolumeAddedFromUrl = (imageOptions, volume) => {
console.log('volume added from url')
console.log('imageOptions: ', imageOptions)
console.log('volume: ', volume)
}
onVolumeUpdated: (() => void) = ...

callback function to run when updateGLVolume is called (most users will not need to use

niivue.onVolumeUpdated = () => {
console.log('volume updated')
}
onWarn: (() => void) = ...

callback function to run when niivue reports a warning

niivue.onWarn = (warn) => {
console.log('warn: ', warn)
}

Methods

  • Add a 3D Label

    Parameters

    • text: string

      text of the label

    • style: NVLabel3DStyle

      label style

    • Optionalpoints: number[] | number[][]
    • Optionalanchor: LabelAnchorPoint
    • OptionalonClick: ((label: NVLabel3D) => void)
        • (label): void
        • Parameters

          • label: NVLabel3D

          Returns void

    Returns NVLabel3D

  • add a new mesh to the canvas

    Parameters

    • mesh: NVMesh

      the new mesh to add to the canvas

    Returns void

    niivue = new Niivue()
    niivue.addMesh(NVMesh.loadFromUrl({url:'../someURL.gii'}))
  • add a new volume to the canvas

    Parameters

    • volume: NVImage

      the new volume to add to the canvas

    Returns void

    niivue = new Niivue()
    niivue.addVolume(NVImage.loadFromUrl({url:'../someURL.nii.gz'}))
  • Not documented publicly for now test if two arrays have equal values for each element

    Parameters

    • a: unknown[]

      the first array

    • b: unknown[]

      the second array

    Returns boolean

    Niivue.arrayEquals(a, b)

    TODO this should maybe just use array-equal from NPM
  • attach the Niivue instance to the webgl2 canvas by element id

    Parameters

    • id: string

      the id of an html canvas element

    • isAntiAlias: any = null

      determines if anti-aliasing is requested (if not specified, AA usage depends on hardware)

    Returns Promise<Niivue>

    niivue = new Niivue().attachTo('gl')
    
    niivue.attachTo('gl')
    
  • attach the Niivue instance to a canvas element directly

    Parameters

    • canvas: HTMLCanvasElement

      the canvas element reference

    • isAntiAlias: boolean = null

    Returns Promise<Niivue>

    niivue = new Niivue()
    niivue.attachToCanvas(document.getElementById(id))
  • Sync the scene controls (orientation, crosshair location, etc.) from one Niivue instance to others. useful for using one canvas to drive another.

    Parameters

    • otherNV: Niivue | Niivue[]

      the other Niivue instance(s)

    • syncOpts: {
          2d: boolean;
          3d: boolean;
      } = ...
      • 2d: boolean
      • 3d: boolean

    Returns void

    niivue1 = new Niivue()
    niivue2 = new Niivue()
    niivue3 = new Niivue()
    niivue1.broadcastTo(niivue2)
    niivue1.broadcastTo([niivue2, niivue3])
  • calculate the the min and max voxel indices from an array of two values (used in selecting intensities with the selection box)

    Parameters

    • array: number[]

      an array of two values

    Returns number[]

    an array of two values representing the min and max voxel indices

  • clone a volume and return a new volume

    Parameters

    • index: number

      the index of the volume to clone

    Returns NVImage

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

    niivue = new Niivue()
    niivue.cloneVolume(0)
  • close drawing: make sure you have saved any changes before calling this!

    Returns void

    niivue.closeDrawing();
    
  • query all available color maps that can be applied to volumes

    Returns string[]

    an array of colormap strings

    niivue = new Niivue()
    colormaps = niivue.colormaps()
  • FreeSurfer-style conform reslices any image to a 256x256x256 volume with 1mm voxels

    Parameters

    • volume: NVImage

      input volume to be re-oriented, intensity-scaled and resliced

    • toRAS: boolean = false

      reslice to row, column slices to right-anterior-superior not left-inferior-anterior (default false).

    • isLinear: boolean = true

      reslice with linear rather than nearest-neighbor interpolation (default true).

    • asFloat32: boolean = false

      use Float32 datatype rather than Uint8 (default false).

    • isRobustMinMax: boolean = false

      clamp intensity with robust min max (~2%..98%) instead of FreeSurfer (0%..99.99%) (default false).

    Returns Promise<NVImage>

  • Parameters

    • fragmentShaderText: string

      custom fragment shader.

    • name: string = 'Custom'

      title for new shader.

    Returns {
        Frag: string;
        Name: string;
        shader: Shader;
    }

    created custom mesh shader

    • Frag: string
    • Name: string
    • shader: Shader
  • reduce complexity of FreeSurfer mesh

    Parameters

    • mesh: number

      identity of mesh to change

    • order: number = 3

      decimation order 0..6

    Returns boolean

    boolean false if mesh is not hierarchical or of lower order

    niivue.decimateHierarchicalMesh(niivue.meshes[0].id, 4)
    
  • dilate drawing so all voxels are colored. works on drawing with multiple colors

    Returns void

    niivue.drawGrowCut();
    
  • Performs a 1-voxel binary dilation on a connected cluster within the drawing mask using the drawFloodFillCore function.

    Parameters

    • seedXYZ: number[]

      voxel index of the seed voxel in the mask array.

    • neighbors: 6 | 18 | 26 = 6

      Number of neighbors to consider for connectivity and dilation (6, 18, or 26).

    Returns void

  • display a lightbox or montage view

    Parameters

    • mosaicStr: string

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

    Returns void

    niivue.setSliceMosaicString("A -10 0 20");
    
  • remove dark voxels in air

    Parameters

    • levels: number = 2

      (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

    niivue.drawOtsu(3);
    
  • generates HTML of current scene

    Parameters

    • canvasId: string = 'gl1'

      id of canvas NiiVue will be attached to

    • esm: string

      bundled version of NiiVue

    Returns Promise<string>

    HTML with javascript of the current scene

    const template = `<html><body><canvas id="gl1"></canvas><script type="module" async>
    %%javascript%%</script></body></html>`;
    nv1.generateHTML("page.html", esm);
  • generates JavaScript to load the current scene as a document

    Parameters

    • canvasId: string

      id of canvas NiiVue will be attached to

    • esm: string

      bundled version of NiiVue

    Returns Promise<string>

    const javascript = this.generateLoadDocumentJavaScript("gl1");
    const html = `<html><body><canvas id="gl1"></canvas><script type="module" async>
    ${javascript}</script></body></html>`;
  • basic statistics for selected voxel-based image

    Parameters

    • 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
      • OptionaldrawingIsMask?: boolean
      • OptionalendVox?: number[]
      • Optionallayer?: number
      • Optionalmasks?: number[]
      • OptionalroiIsMask?: boolean
      • OptionalstartVox?: number[]

    Returns Descriptive

    numeric values to describe image or regions of images

    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
    });
  • determine active 3D volume from 4D time series

    Parameters

    • id: string

      the ID of the 4D NVImage

    Returns number

    currently selected volume (indexed from 0)

    nv1.getFrame4D(nv1.volumes[0].id);
    
  • 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

    • id: string

      the id string to search for

    Returns number

    NiiVue#getVolumeIndexByID

    niivue = new Niivue()
    niivue.getOverlayIndexByID(someVolume.id)
  • Detect if display is using radiological or neurological convention.

    Returns boolean

    radiological convention status

    let rc = niivue.getRadiologicalConvention()
    
  • 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

    • id: string

      the id string to search for

    Returns number

    niivue = new Niivue()
    niivue.getVolumeIndexByID(someVolume.id)
  • returns the index of the mesh vertex that is closest to the provided coordinates

    Parameters

    • mesh: number
    • Xmm: number

      location in left/right dimension

    • Ymm: number

      location in posterior/anterior dimension

    • Zmm: number

      location 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

    niivue.indexNearestXYZmm(niivue.meshes[0].id, -22, 42, 13)
    
  • Returns boolean: true if filename ends with mesh extension (TRK, pial, etc)

    Parameters

    • url: string

      filename

    Returns boolean

  • Converts NiiVue scene to JSON

    Returns ExportDocumentData

  • load a connectome specified by json

    Parameters

    • json: Connectome | LegacyConnectome

    Returns this

    Niivue instance

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

    Parameters

    • id: string

      the ID of the 4D NVImage

    Returns Promise<void>

  • Parameters

    • url: string

      URL of NVDocument

    Returns Promise<void>

  • Open drawing

    Parameters

    • fnm: string
    • isBinarize: boolean = false

      if true will force drawing voxels to be either 0 or 1.

    Returns Promise<boolean>

    niivue.loadDrawingFromUrl("../images/lesion.nii.gz");
    
  • Load typeface for colorbars, measurements and orientation text.

    Parameters

    • fontSheetUrl: any = defaultFontPNG
    • 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;
          };
      } = defaultFontMetrics
      • atlas: {
            distanceRange: number;
            height: number;
            size: number;
            type: string;
            width: number;
            yOrigin: string;
        }
        • 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;
        }
        • ascender: number
        • descender: number
        • emSize: number
        • lineHeight: number
        • underlineThickness: number
        • underlineY: number

    Returns Promise<void>

    niivue.loadMatCapTexture("Cortex");
    
  • Load an image or mesh from an array buffer

    Parameters

    • buffer: ArrayBuffer

      ArrayBuffer with the entire contents of a mesh or volume

    • name: string

      string of filename, extension used to infer type (NIfTI, MGH, MZ3, etc)

    Returns Promise<void>

  • Load a mesh or image from a file object

    Parameters

    • file: File

      File object

    Returns Promise<void>

  • Load matcap for illumination model.

    Parameters

    • bmpUrl: string

    Returns Promise<WebGLTexture>

    niivue.loadMatCapTexture("Cortex");
    
  • load an array of meshes

    Parameters

    • meshList: LoadFromUrlParams[]

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

    Returns Promise<Niivue>

    Niivue instance

    niivue = new Niivue()
    niivue.loadMeshes([{url: 'someMesh.gii'}])
  • load an array of volume objects

    Parameters

    • volumeList: ImageFromUrlOptions[]

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

    Returns Promise<Niivue>

    returns the Niivue instance

    niivue = new Niivue()
    niivue.loadVolumes([{url: 'someImage.nii.gz}, {url: 'anotherImage.nii.gz'}])
  • retrieve all currently loaded meshes

    Parameters

    • sort: boolean = true

      sort output alphabetically

    Returns string[]

    list of available mesh shader names

    niivue.meshShaderNames();
    
  • move crosshair a fixed number of voxels (not mm)

    Parameters

    • x: number

      translate left (-) or right (+)

    • y: number

      translate posterior (-) or +anterior (+)

    • z: number

      translate inferior (-) or superior (+)

    Returns void

    niivue.moveCrosshairInVox(1, 0, 0)
    
  • Move a volume down one index position in the stack of loaded volumes. This moves it down one layer

    Parameters

    Returns void

    niivue = new Niivue()
    niivue.moveVolumeDown(this.volumes[1]) // move the second image to the background position (it was 1 index, now will be 0)
  • Move a volume to the bottom of the stack of loaded volumes. The volume will become the background

    Parameters

    Returns void

    niivue = new Niivue()
    niivue.moveVolumeToBottom(this.volumes[3]) // move the 4th volume to the 0 position. It will be the new background
  • Move a volume to the top position in the stack of loaded volumes. This will be the top layer

    Parameters

    Returns void

    niivue = new Niivue()
    niivue.moveVolumeToTop(this.volumes[0]) // move the background image to the top layer position
  • Move a volume up one index position in the stack of loaded volumes. This moves it up one layer

    Parameters

    Returns void

    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)
  • copy drawing bitmap from CPU to GPU storage and redraw the screen

    Parameters

    • isForceRedraw: boolean = true

      refreshes scene immediately (default true)

    • useClickToSegmentBitmap: boolean = false

    Returns void

    niivue.refreshDrawing();
    
  • remove dark voxels in air

    Parameters

    • level: number = 5

      (1-5) larger values for more preserved voxels

    • volIndex: number = 0

      volume to dehaze

    Returns void

    niivue.removeHaze(3, 0);
    
  • Remove a triangulated mesh, connectome or tractogram

    Parameters

    Returns void

    niivue = new Niivue()
    niivue.removeMesh(this.meshes[3])
  • Remove a triangulated mesh, connectome or tractogram

    Parameters

    • url: string

      URL of mesh to delete

    Returns void

    niivue.removeMeshByUrl('../images/cit168.mz3')
    
  • Remove a volume

    Parameters

    Returns void

    niivue = new Niivue()
    niivue.removeVolume(this.volumes[3])
  • Remove a volume by index

    Parameters

    • index: number

      of volume to remove

    Returns void

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

    Parameters

    • mesh: number

    Returns void

    niivue.reverseFaces(niivue.meshes[0].id)
    
  • save the entire scene (objects and settings) as a document

    Parameters

    • fileName: string = 'untitled.nvd'

      the name of the document storing the scene

    • compress: boolean = true

      whether the file should be compressed

    Returns Promise<void>

    niivue.saveDocument("niivue.basic.nvd")
    
  • save current scene as HTML

    Parameters

    • fileName: string = 'untitled.html'

      the name of the HTML file

    • canvasId: string = 'gl1'

      id of canvas NiiVue will be attached to

    • esm: string

      bundled version of NiiVue

    Returns Promise<void>

  • save voxel-based image to disk

    Parameters

    • options: SaveImageOptions = defaultSaveImageOptions

    Returns boolean | Uint8Array

    niivue.saveImage({ filename: "myimage.nii.gz", isSaveDrawing: true });
    
  • save webgl2 canvas as png format bitmap

    Parameters

    • filename: string = 'niivue.png'

      filename for screen capture

    Returns Promise<void>

    niivue.saveScene('test.png');
    
  • control whether voxel overlays are combined using additive (emission) or traditional (transmission) blending.

    Parameters

    • isAdditiveBlend: boolean

      emission (true) or transmission (false) mixing

    Returns void

    niivue.isAdditiveBlend(true)
    
  • update the clip plane orientation in 3D view mode

    Parameters

    • depthAzimuthElevation: number[]

    Returns void

    niivue = new Niivue()
    niivue.setClipPlane([42, 42])
  • set the color of the 3D clip plane

    Parameters

    • color: number[]

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

    Returns void

    niivue.setClipPlaneColor([1, 1, 1, 0.5]) // white, transparent
    
  • adjust thickness of the 3D clip plane

    Parameters

    • thick: number

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

    Returns void

    niivue.setClipPlaneThick(0.3) // thin slab
    
  • set the clipping region for volume rendering

    Parameters

    • low: number[]
    • high: number[]

    Returns void

    niivue.setClipPlaneColor([0.0, 0.0, 0.2], [1.0, 1.0, 0.7]) // remove inferior 20% and superior 30%
    
  • update the colormap of an image given its ID

    Parameters

    • id: string

      the ID of the NVImage

    • colormap: string

      the name of the colormap to use

    Returns void

    niivue.setColormap(niivue.volumes[0].id,, 'red')
    
  • use given color map for negative voxels in image

    Parameters

    • id: string

      the ID of the NVImage

    • colormapNegative: string

      the name of the colormap to use

    Returns void

    niivue = new Niivue()
    niivue.setColormapNegative(niivue.volumes[1].id,"winter");
  • determine if text appears at corner (true) or sides of 2D slice.

    Parameters

    • isCornerOrientationText: boolean

      controls position of text

    Returns void

    niivue.setCornerOrientationText(true)
    
  • set the crosshair and colorbar outline color

    Parameters

    • color: number[]

      an RGBA array. values range from 0 to 1

    Returns void

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

    Parameters

    • crosshairWidth: number

    Returns void

    niivue.crosshairWidth(2)
    
  • Define a new GLSL shader program to influence mesh coloration

    Parameters

    • fragmentShaderText: string = ''

      custom fragment shader.

    • name: string = 'Custom'

    Returns number

    index of the new shader (for setMeshShader)

  • Reset scene to default settings.

    Parameters

    • options: Partial<NVConfigOptions> = {}
    • resetBriCon: boolean = false

      also reset contrast (default false).

    Returns void

    niivue.nv1.setDefaults(opts, true);
    
  • does dragging over a 2D slice create a drawing?

    Parameters

    • trueOrFalse: boolean

      enabled (true) or not (false)

    Returns void

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

    Parameters

    • opacity: number

      translucency of drawing

    Returns void

    niivue.setDrawOpacity(0.7)
    
  • show desired 3D volume from 4D time series

    Parameters

    • id: string

      the ID of the 4D NVImage

    • frame4D: number

      frame to display (indexed from zero)

    Returns void

    nv1.setFrame4D(nv1.volumes[0].id, 42);
    
  • adjust screen gamma. Low values emphasize shadows but can appear flat, high gamma hides shadow details.

    Parameters

    • gamma: number = 1.0

      selects luminance, default is 1

    Returns void

    niivue.setGamma(1.0);
    
  • determine proportion of screen real estate devoted to rendering in multiplanar view.

    Parameters

    • fraction: number

      proportion of screen devoted to primary (hero) image (0 to disable)

    Returns void

    niivue.setHeroImage(0.5)
    
  • Force WebGL canvas to use high resolution display, regardless of browser defaults.

    Parameters

    • isHighResolutionCapable: boolean

      allow high-DPI display

    Returns void

    niivue.setHighResolutionCapable(true);
    
  • select between nearest and linear interpolation for voxel based images

    Parameters

    • isNearest: boolean

      whether nearest neighbor interpolation is used, else linear interpolation

    Returns void

    niivue.setInterpolation(true);
    
  • reverse triangle winding of mesh (swap front and back faces)

    Parameters

    • mesh: number

      identity of mesh to change

    • layer: number

      selects the mesh overlay (e.g. GIfTI or STC file)

    • key: keyof NVMeshLayer

      attribute to change

    • val: number

    Returns void

    niivue.setMeshLayerProperty(niivue.meshes[0].id, 0, 'frame4D', 22)
    
  • change property of mesh, tractogram or connectome

    Parameters

    • id: number

      identity of mesh to change

    • key: keyof NVMesh

      attribute to change

    • val: number

    Returns void

    niivue.setMeshProperty(niivue.meshes[0].id, 'fiberLength', 42)
    
  • 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

    • id: number

      id of mesh to change

    • meshShaderNameOrNumber: number = 2

      identify shader for usage

    Returns void

    niivue.setMeshShader('toon');
    
  • Limit visibility of mesh in front of a 2D image. Requires world-space mode.

    Parameters

    • meshThicknessOn2D: number

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

    Returns void

    niivue.setMeshThicknessOn2D(42)
    
  • modulate intensity of one image based on intensity of another

    Parameters

    • idTarget: string

      the ID of the NVImage to be biased

    • idModulation: string

      the ID of the NVImage that controls bias (empty string to disable modulation)

    • modulateAlpha: number = 0

      does the modulation influence alpha transparency (values greater than 1).

    Returns void

    niivue.setModulationImage(niivue.volumes[0].id, niivue.volumes[1].id);
    
  • control placement of 2D slices.

    Parameters

    • layout: number

      AUTO: 0, COLUMN: 1, GRID: 2, ROW: 3,

    Returns void

    niivue.setMultiplanarLayout(2)
    
  • insert a gap between slices of a mutliplanar view.

    Parameters

    • pixels: number

      spacing between tiles of multiplanar view

    Returns void

    niivue.setMultiplanarPadPixels(4)
    
  • set the opacity of a volume given by volume index

    Parameters

    • volIdx: number

      the volume index of the volume to change

    • newOpacity: number

      the opacity value. valid values range from 0 to 1. 0 will effectively remove a volume from the scene

    Returns void

    niivue = new Niivue()
    niivue.setOpacity(0, 0.5) // make the first volume transparent
  • adjust offset position and scale of 2D sliceScale

    Parameters

    • xyzmmZoom: vec4

      first three components are spatial, fourth is scaling

    Returns void

    niivue.setPan2Dxyzmm([5,-4, 2, 1.5])
    
  • determine color and style of drawing

    Parameters

    • penValue: number

      sets the color of the pen

    • isFilledPen: boolean = false

      determines if dragging creates flood-filled shape

    Returns void

    niivue.setPenValue(1, true)
    
  • control whether 2D slices use radiological or neurological convention.

    Parameters

    • isRadiologicalConvention: boolean

      new display convention

    Returns void

    niivue.setRadiologicalConvention(true)
    
  • set rotation of 3D render view

    Parameters

    • a: number
    • e: number

    Returns void

    niivue.setRenderAzimuthElevation(45, 15)
    
  • darken crevices and brighten corners when 3D rendering drawings.

    Parameters

    • ao: number

    Returns void

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

    Parameters

    • scale: number

      the new scale value

    Returns void

    niivue.setScale(2) // zoom some
    
  • set the selection box color. A selection box is drawn when you right click and drag to change image contrast

    Parameters

    • color: number[]

      an RGBA array. values range from 0 to 1

    Returns void

    niivue = new Niivue()
    niivue.setSelectionBoxColor([0, 1, 0, 0.5]) // set to transparent green
  • control 2D slice view mode.

    Parameters

    • isSliceMM: boolean

      control 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

    niivue.setSliceMM(true)
    
  • Create a custom multi-slice mosaic (aka lightbox, montage) view.

    Parameters

    • str: string

      description of mosaic.

    Returns void

    niivue.setSliceMosaicString("A 0 20 C 30 S 42")
    
  • set the slice type. This changes the view mode

    Parameters

    • st: SLICE_TYPE

    Returns this

    niivue = new Niivue()
    niivue.setSliceType(Niivue.sliceTypeMultiplanar)
  • set the index of a volume. This will change it's ordering and appearance if there are multiple volumes loaded.

    Parameters

    • volume: NVImage

      the volume to update

    • toIndex: number = 0

      the index to move the volume to. The default is the background (0 index)

    Returns void

    niivue = new Niivue()
    niivue.setVolume(someVolume, 1) // move it to the second position in the array of loaded volumes (0 is the first position)
  • set proportion of volume rendering influenced by selected matcap.

    Parameters

    • gradientAmount: number = 0.0

      amount of matcap (0..1), default 0 (matte, surface normal does not influence color)

    Returns Promise<void>

    niivue.setVolumeRenderIllumination(0.6);
    
  • convert spherical AZIMUTH, ELEVATION to Cartesian

    Parameters

    • azimuth: number

      azimuth number

    • elevation: number

      elevation number

    Returns number[]

    the converted [x, y, z] coordinates

    niivue = new Niivue()
    xyz = niivue.sph2cartDeg(42, 42)
  • Sync the scene controls (orientation, crosshair location, etc.) from one Niivue instance to another. useful for using one canvas to drive another.

    Parameters

    • otherNV: Niivue | Niivue[]

      the other Niivue instance that is the main controller

    • syncOpts: {
          2d: boolean;
          3d: boolean;
      } = ...
      • 2d: boolean
      • 3d: boolean

    Returns void

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

    use broadcastTo instead

  • 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

    niivue = new Niivue()
    niivue.updateGLVolume()