@cornerstonejs/core
Version:
Cornerstone3D Core
80 lines (79 loc) • 2.88 kB
JavaScript
const VIEWPORT_ELEMENT = 'viewport-element';
const CANVAS_CSS_CLASS = 'cornerstone-canvas';
export const EPSILON = 1e-4;
let canvasCreator;
export function createCanvas(element, width = 512, height = 512) {
const canvas = canvasCreator
? canvasCreator(width, height)
: document.createElement('canvas');
if (!element) {
return canvas;
}
canvas.style.position = 'absolute';
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.style.imageRendering = 'pixelated';
canvas.classList.add(CANVAS_CSS_CLASS);
element.appendChild(canvas);
return canvas;
}
export function createViewportElement(element) {
const div = document.createElement('div');
div.style.position = 'relative';
div.style.width = '100%';
div.style.height = '100%';
div.style.overflow = 'hidden';
div.classList.add(VIEWPORT_ELEMENT);
element.appendChild(div);
return div;
}
export function setCanvasCreator(canvasCreatorArg) {
canvasCreator = canvasCreatorArg;
}
export function updateCanvasSizeAndAspectRatio(canvas, extentOrOffscreen) {
if (extentOrOffscreen === undefined) {
const devicePixelRatio = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
const w = Math.round(rect.width * devicePixelRatio);
const h = Math.round(rect.height * devicePixelRatio);
if (w > 0 && h > 0) {
canvas.width = w;
canvas.height = h;
canvas.style.aspectRatio = `${w} / ${h}`;
}
return undefined;
}
const { width: targetW, height: targetH } = extentOrOffscreen;
if (targetW < 1 || targetH < 1) {
return false;
}
const needsUpdate = canvas.width !== targetW || canvas.height !== targetH;
if (needsUpdate) {
canvas.width = targetW;
canvas.height = targetH;
canvas.style.aspectRatio = `${targetW} / ${targetH}`;
return true;
}
return false;
}
export function getOrCreateCanvas(element) {
const canvasSelector = `canvas.${CANVAS_CSS_CLASS}`;
const viewportElement = `div.${VIEWPORT_ELEMENT}`;
const internalDiv = element.querySelector(viewportElement) || createViewportElement(element);
const existingCanvas = internalDiv.querySelector(canvasSelector);
if (existingCanvas) {
return existingCanvas;
}
const canvas = createCanvas(internalDiv);
const rect = internalDiv.getBoundingClientRect();
const devicePixelRatio = window.devicePixelRatio || 1;
const width = Math.ceil(rect.width * devicePixelRatio);
const height = Math.ceil(rect.height * devicePixelRatio);
if (width > 0 && height > 0) {
canvas.width = width;
canvas.height = height;
canvas.style.aspectRatio = `${width} / ${height}`;
}
return canvas;
}
export default getOrCreateCanvas;