import NiiVue from '@niivue/niivue'
const anteriorBtn = document.getElementById('anteriorBtn')
const antiAliasCheck = document.getElementById('antiAliasCheck')
const closeBtn = document.getElementById('closeBtn')
const gl1 = document.getElementById('gl1')
const inferiorBtn = document.getElementById('inferiorBtn')
const leftBtn = document.getElementById('leftBtn')
const loadBtn = document.getElementById('loadBtn')
const loadFile = document.getElementById('loadFile')
const opacitySlider = document.getElementById('opacitySlider')
const overwriteCheck = document.getElementById('overwriteCheck')
const penSize = document.getElementById('penSize')
const penValue = document.getElementById('penValue')
const posteriorBtn = document.getElementById('posteriorBtn')
const rightBtn = document.getElementById('rightBtn')
const rimCheck = document.getElementById('rimCheck')
const saveBtn = document.getElementById('saveBtn')
const segmentCheck = document.getElementById('segmentCheck')
const sliceType = document.getElementById('sliceType')
const statsBtn = document.getElementById('statsBtn')
const superiorBtn = document.getElementById('superiorBtn')
const svgBtn = document.getElementById('svgBtn')
const undoBtn = document.getElementById('undoBtn')
const webgpuCheck = document.getElementById('webgpuCheck')
function setDrawingUI(enabled) {
undoBtn.disabled = !enabled
saveBtn.disabled = !enabled
closeBtn.disabled = !enabled
statsBtn.disabled = !enabled
document.getElementById('report').textContent = text
function ensureDrawing() {
penValue.onchange = function () {
const val = parseInt(this.value, 10)
// Vector (SVG) mode: draw freehand vector polygons (annotation layer) instead
// of painting the raster, and enable the SVG export. Mirrors the slide demos'
const vector = val === 10
nv1.annotationIsEnabled = vector
svgBtn.disabled = !vector
nv1.drawIsEnabled = false // let the annotation layer handle the click
nv1.annotationTool = 'freehand'
nv1.annotationBrushRadius = 1 // <=1 => closed-polygon mode
// "Off" selected — disable pen but keep drawing visible
nv1.drawIsEnabled = false
// Filled: values 4,5,6 map to pen colors 1,2,3
nv1.drawPenValue = val - 3
nv1.drawPenAutoClose = true
// Outline or erase: values 0,1,2,3
nv1.drawPenAutoClose = false
nv1.drawPenFilled = false
const svg = nv1.annotationsToSVG()
alert('Draw a vector shape first (Pen -> Vector (SVG)).')
const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }))
const a = document.createElement('a')
a.download = 'annotations.svg'
penSize.oninput = function () {
nv1.drawPenSize = parseInt(this.value, 10)
opacitySlider.oninput = function () {
nv1.drawOpacity = this.value * 0.01
undoBtn.onclick = () => {
// In Vector (SVG) mode, undo the vector annotation; otherwise the raster stroke.
if (penValue.value === '10') nv1.annotationUndo()
saveBtn.onclick = () => {
nv1.saveDrawing('drawing.nii.gz')
closeBtn.onclick = () => {
loadBtn.onclick = () => {
alert('A drawing is already open. Please close it before loading another.')
async function openDrawing(source) {
const ok = await nv1.loadDrawing(source)
nv1.drawPenAutoClose = false
nv1.drawPenFilled = false
loadFile.onchange = async function () {
const file = loadFile.files?.[0]
const name = file.name.toLowerCase()
if (!name.endsWith('.nii') && !name.endsWith('.nii.gz')) {
alert(`Unsupported file: ${file.name}\nExpected .nii or .nii.gz`)
const ok = await openDrawing(file)
`Could not load ${file.name} as a drawing.\nCheck the browser console for details.`,
sliceType.onchange = () => {
nv1.sliceType = parseInt(sliceType.value, 10)
webgpuCheck.onclick = function () {
nv1.reinitializeView({ backend: this.checked ? 'webgpu' : 'webgl2' })
antiAliasCheck.onchange = async () => {
await nv1.reinitializeView({ isAntiAlias: antiAliasCheck.checked })
leftBtn.onclick = () => nv1.moveCrosshairInVox(-1, 0, 0)
rightBtn.onclick = () => nv1.moveCrosshairInVox(1, 0, 0)
posteriorBtn.onclick = () => nv1.moveCrosshairInVox(0, -1, 0)
anteriorBtn.onclick = () => nv1.moveCrosshairInVox(0, 1, 0)
inferiorBtn.onclick = () => nv1.moveCrosshairInVox(0, 0, -1)
superiorBtn.onclick = () => nv1.moveCrosshairInVox(0, 0, 1)
segmentCheck.onchange = function () {
// The magic wand paints into the drawing, so it needs one open and a pen
// colour selected — "Off" would swallow the click.
if (parseInt(penValue.value, 10) < 1) {
nv1.drawIsClickToSegment = this.checked
this.checked ? 'Click a voxel to grow a region of similar intensity.' : ' ',
statsBtn.onclick = () => {
// Measure the background volume, counting only voxels the drawing covers.
const roi = nv1.getDescriptives({ volumeIndex: 0, isDrawingMask: true })
report('No drawing to measure.')
`Drawn region: ${roi.nVox} voxels, ${roi.volumeML.toFixed(2)} mL | ` +
`mean ${roi.mean.toFixed(1)} +/- ${roi.stdev.toFixed(1)} | ` +
`range ${roi.min.toFixed(1)}..${roi.max.toFixed(1)}`,
overwriteCheck.onchange = function () {
nv1.drawIsFillOverwriting = this.checked
rimCheck.onchange = function () {
nv1.drawRimOpacity = this.checked ? 1 : -1
function handleLocationChange(data) {
document.getElementById('location').innerHTML = ` ${data.string}`
// WebKit (Safari, and every iOS browser) runs WebGPU about 4x slower with
// anti-aliasing on (#381), so it defaults off there and on elsewhere (as slides.js).
/AppleWebKit/.test(navigator.userAgent) &&
!/Chrome|Chromium|Edg\//.test(navigator.userAgent) // iOS Edge (EdgiOS) is WebKit
antiAliasCheck.checked = !isWebKit
const nv1 = new NiiVue({ isAntiAlias: antiAliasCheck.checked })
nv1.addEventListener('locationChange', (e) => handleLocationChange(e.detail))
nv1.addEventListener('clickToSegment', (e) => {
`Segmented ${d.voxelCount} voxels (${d.mL.toFixed(2)} mL) ` +
`from voxel ${d.seed.join(', ')}${d.hitCap ? ' - stopped at the voxel cap' : ''}`,
await nv1.attachToCanvas(gl1)
await nv1.loadVolumes({ url: '/volumes/mni152.nii.gz' })
await openDrawing('/volumes/drawing.nii.gz')