All files / packages/tools/src/utilities/voi/colorbar ColorbarCanvas.ts

1.01% Statements 1/99
0% Branches 0/52
0% Functions 0/19
1.03% Lines 1/97

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291                          1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import { IColorMapPreset } from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction/ColorMaps';
import { utilities } from '@cornerstonejs/core';
import interpolateVec3 from '../../math/vec3/interpolateVec3';
import { ColorbarCanvasProps } from './types/ColorbarCanvasProps';
import type { ColorbarImageRange, ColorbarVOIRange } from './types';
import type { ColorbarSize } from './types/ColorbarSize';
import {
  isRangeValid,
  areColorbarRangesEqual,
  isColorbarSizeValid,
  areColorbarSizesEqual,
} from './common';
 
const { clamp } = utilities;
 
/**
 * Canvas referenced by the color bar where the colormap is rendered. It may
 * show the full image range or only the VOI range.
 */
class ColorbarCanvas {
  private _canvas: HTMLCanvasElement;
  private _imageRange: ColorbarImageRange;
  private _voiRange: ColorbarVOIRange;
  private _colormap: IColorMapPreset;
  private _showFullImageRange: boolean;
 
  constructor(props: ColorbarCanvasProps) {
    ColorbarCanvas.validateProps(props);
 
    const {
      colormap,
      size = { width: 20, height: 100 },
      imageRange = { lower: 0, upper: 1 },
      voiRange = { lower: 0, upper: 1 },
      container,
      showFullPixelValueRange = false,
    } = props;
 
    this._colormap = colormap;
    this._imageRange = imageRange;
    this._voiRange = voiRange;
    this._showFullImageRange = showFullPixelValueRange;
    this._canvas = this._createRootElement(size);
 
    if (container) {
      this.appendTo(container);
    }
  }
 
  public get colormap(): IColorMapPreset {
    return this._colormap;
  }
 
  public set colormap(colormap: IColorMapPreset) {
    this._colormap = colormap;
    this.render();
  }
 
  public get size(): ColorbarSize {
    const { width, height } = this._canvas;
    return { width, height };
  }
 
  public set size(size: ColorbarSize) {
    const { _canvas: canvas } = this;
 
    if (!isColorbarSizeValid(size) || areColorbarSizesEqual(canvas, size)) {
      return;
    }
 
    this._setCanvasSize(canvas, size);
    this.render();
  }
 
  public get imageRange(): ColorbarImageRange {
    return { ...this._imageRange };
  }
 
  public set imageRange(imageRange: ColorbarImageRange) {
    if (
      !isRangeValid(imageRange) ||
      areColorbarRangesEqual(imageRange, this._imageRange)
    ) {
      return;
    }
 
    this._imageRange = imageRange;
    this.render();
  }
 
  public get voiRange(): ColorbarVOIRange {
    return { ...this._voiRange };
  }
 
  public set voiRange(voiRange: ColorbarVOIRange) {
    if (
      !isRangeValid(voiRange) ||
      areColorbarRangesEqual(voiRange, this._voiRange)
    ) {
      return;
    }
 
    this._voiRange = voiRange;
    this.render();
  }
 
  public get showFullImageRange(): boolean {
    return this._showFullImageRange;
  }
 
  public set showFullImageRange(showFullImageRange: boolean) {
    if (showFullImageRange === this._showFullImageRange) {
      return;
    }
 
    this._showFullImageRange = showFullImageRange;
    this.render();
  }
 
  public appendTo(container: HTMLElement) {
    container.appendChild(this._canvas);
    this.render();
  }
 
  public dispose() {
    const { _canvas: canvas } = this;
    const { parentElement } = canvas;
 
    parentElement?.removeChild(canvas);
  }
 
  private static validateProps(props: ColorbarCanvasProps) {
    const { size, imageRange, voiRange } = props;
 
    if (size && !isColorbarSizeValid(size)) {
      throw new Error('Invalid "size"');
    }
 
    if (imageRange && !isRangeValid(imageRange)) {
      throw new Error('Invalid "imageRange"');
    }
 
    if (voiRange && !isRangeValid(voiRange)) {
      throw new Error('Invalid "voiRange"');
    }
  }
 
  private _setCanvasSize(canvas: HTMLCanvasElement, size: ColorbarSize) {
    const { width, height } = size;
 
    canvas.width = width;
    canvas.height = height;
 
    Object.assign(canvas.style, {
      width: `${width}px`,
      height: `${height}px`,
    });
  }
 
  private _createRootElement(size: ColorbarSize) {
    const canvas = document.createElement('canvas');
 
    Object.assign(canvas.style, {
      position: 'absolute',
      top: '0',
      left: '0',
      pointerEvents: 'none',
      boxSizing: 'border-box',
    });
 
    this._setCanvasSize(canvas, size);
 
    return canvas;
  }
 
  private render(): void {
    if (!this._canvas.isConnected) {
      return;
    }
 
    const { _colormap: colormap } = this;
    const { RGBPoints: rgbPoints } = colormap;
    const colorsCount = rgbPoints.length / 4;
 
    // Returns a color point from rgbPoints. Each point has position, red,
    // green and blue components which means each point has an offset equal
    // to `4 * index`
    const getColorPoint = (index) => {
      const offset = 4 * index;
 
      // It can get out of bounds when `voiRange.upper` is smaller than
      // `imageRange.upper`. It's also checking if is smaller than zero
      // for safety only because that should never happens.
      if (index < 0 || index >= colorsCount) {
        return;
      }
 
      return {
        index,
        position: rgbPoints[offset],
        color: [
          rgbPoints[offset + 1],
          rgbPoints[offset + 2],
          rgbPoints[offset + 3],
        ],
      };
    };
 
    const { width, height } = this._canvas;
    const canvasContext = this._canvas.getContext('2d');
    const isHorizontal = width > height;
    const maxValue = isHorizontal ? width : height;
    const { _voiRange: voiRange } = this;
    const range = this._showFullImageRange ? this._imageRange : { ...voiRange };
 
    const { windowWidth } = utilities.windowLevel.toWindowLevel(
      voiRange.lower,
      voiRange.upper
    );
 
    let previousColorPoint = undefined;
    let currentColorPoint = getColorPoint(0);
 
    // Starts from `range.lower` incrementing by incRawPixelValue on each iteration
    const incRawPixelValue = (range.upper - range.lower) / (maxValue - 1);
    let rawPixelValue = range.lower;
 
    for (let i = 0; i < maxValue; i++) {
      const tVoiRange = (rawPixelValue - voiRange.lower) / windowWidth;
 
      // Find the color in a linear way (O(n) complexity).
      // currentColorPoint shall move to the next color until tVoiRange is smaller
      // than or equal to next color position.
      if (currentColorPoint) {
        for (let i = currentColorPoint.index; i < colorsCount; i++) {
          if (tVoiRange <= currentColorPoint.position) {
            break;
          }
 
          previousColorPoint = currentColorPoint;
          currentColorPoint = getColorPoint(i + 1);
        }
      }
 
      let normColor;
 
      // For:
      //   - firstColorPoint = getColorPoint(0)
      //   - secondColorPoint = getColorPoint(1)
      //   - lastColorPoint = getColorPoint(colorsCount - 1)
      // Then
      //   - previousColorPoint shall be undefined when tVoiRange < firstColorPoint.position
      //   - currentColorPoint shall be undefined when tVoiRange > lastColorPoint.position
      //   - previousColorPoint and currentColorPoint will be defined when
      //     currentColorPoint.position is between secondColorPoint.position and
      //     lastColorPoint.position.
      if (!previousColorPoint) {
        normColor = [...currentColorPoint.color];
      } else if (!currentColorPoint) {
        normColor = [...previousColorPoint.color];
      } else {
        const tColorRange =
          (tVoiRange - previousColorPoint.position) /
          (currentColorPoint.position - previousColorPoint.position);
 
        normColor = interpolateVec3(
          previousColorPoint.color,
          currentColorPoint.color,
          tColorRange
        );
      }
 
      const color = normColor.map((color) =>
        clamp(Math.round(color * 255), 0, 255)
      );
 
      canvasContext.fillStyle = `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
 
      if (isHorizontal) {
        canvasContext.fillRect(i, 0, 1, height);
      } else {
        canvasContext.fillRect(0, height - i - 1, width, 1);
      }
 
      rawPixelValue += incRawPixelValue;
    }
  }
}
 
export { ColorbarCanvas as default, ColorbarCanvas };