excalidraw/src/renderer/renderScene.ts

285 lines
7.9 KiB
TypeScript
Raw Normal View History

import { RoughCanvas } from "roughjs/bin/canvas";
import { RoughSVG } from "roughjs/bin/svg";
import { ExcalidrawElement } from "../element/types";
import { getElementAbsoluteCoords, handlerRectangles } from "../element";
import { roundRect } from "./roundRect";
import { SceneState } from "../scene/types";
import {
getScrollBars,
SCROLLBAR_COLOR,
2020-01-24 12:04:54 +02:00
SCROLLBAR_WIDTH,
} from "../scene/scrollbars";
import { getZoomTranslation } from "../scene/zoom";
import { renderElement, renderElementToSvg } from "./renderElement";
export function renderScene(
elements: readonly ExcalidrawElement[],
Fix issues related to history (#701) * Separate UI from Canvas * Explicitly define history recording * ActionManager: Set syncActionState during construction instead of in every call * Add commit to history flag to necessary actions * Disable undoing during multiElement * Write custom equality function for UI component to render it only when specific props and elements change * Remove stale comments about history skipping * Stop undo/redoing when in resizing element mode * wip * correctly reset resizingElement & add undo check * Separate selection element from the rest of the array and stop redrawing the UI when dragging the selection * Remove selectionElement from local storage * Remove unnecessary readonly type casting in actionFinalize * Fix undo / redo for multi points * Fix an issue that did not update history when elements were locked * Disable committing to history for noops - deleteSelected without deleting anything - Basic selection * Use generateEntry only inside history and pass elements and appstate to history * Update component after every history resume * Remove last item from the history only if in multi mode * Resume recording when element type is not selection * ensure we prevent hotkeys only on writable elements * Remove selection clearing from history * Remove one point arrows as they are invisibly small * Remove shape of elements from local storage * Fix removing invisible element from the array * add missing history resuming cases & simplify slice * fix lint * don't regenerate elements if no elements deselected * regenerate elements array on selection * reset state.selectionElement unconditionally * Use getter instead of passing appState and scene data through functions to actions * fix import Co-authored-by: David Luzar <luzar.david@gmail.com>
2020-02-05 22:47:10 +04:00
selectionElement: ExcalidrawElement | null,
rc: RoughCanvas,
canvas: HTMLCanvasElement,
sceneState: SceneState,
// extra options, currently passed by export helper
{
offsetX,
offsetY,
renderScrollbars = true,
2020-01-24 12:04:54 +02:00
renderSelection = true,
}: {
offsetX?: number;
offsetY?: number;
renderScrollbars?: boolean;
renderSelection?: boolean;
2020-01-24 12:04:54 +02:00
} = {},
): boolean {
if (!canvas) {
return false;
}
// Use offsets insteads of scrolls if available
sceneState = {
...sceneState,
scrollX: typeof offsetX === "number" ? offsetX : sceneState.scrollX,
scrollY: typeof offsetY === "number" ? offsetY : sceneState.scrollY,
};
const context = canvas.getContext("2d")!;
// Get initial scale transform as reference for later usage
const initialContextTransform = context.getTransform();
// When doing calculations based on canvas width we should used normalized one
const normalizedCanvasWidth =
canvas.width / getContextTransformScaleX(initialContextTransform);
const normalizedCanvasHeight =
canvas.height / getContextTransformScaleY(initialContextTransform);
// Handle zoom scaling
function scaleContextToZoom() {
context.setTransform(
getContextTransformScaleX(initialContextTransform) * sceneState.zoom,
0,
0,
getContextTransformScaleY(initialContextTransform) * sceneState.zoom,
getContextTransformTranslateX(context.getTransform()),
getContextTransformTranslateY(context.getTransform()),
);
}
// Handle zoom translation
const zoomTranslation = getZoomTranslation(canvas, sceneState.zoom);
function translateContextToZoom() {
context.setTransform(
getContextTransformScaleX(context.getTransform()),
0,
0,
getContextTransformScaleY(context.getTransform()),
getContextTransformTranslateX(initialContextTransform) -
zoomTranslation.x,
getContextTransformTranslateY(initialContextTransform) -
zoomTranslation.y,
);
}
// Paint background
context.save();
if (typeof sceneState.viewBackgroundColor === "string") {
const hasTransparence =
sceneState.viewBackgroundColor === "transparent" ||
sceneState.viewBackgroundColor.length === 5 ||
sceneState.viewBackgroundColor.length === 9;
if (hasTransparence) {
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
}
context.fillStyle = sceneState.viewBackgroundColor;
context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
} else {
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
}
context.restore();
// Paint visible elements
const visibleElements = elements.filter(element =>
isVisibleElement(
element,
normalizedCanvasWidth,
normalizedCanvasHeight,
sceneState,
),
);
context.save();
scaleContextToZoom();
translateContextToZoom();
context.translate(sceneState.scrollX, sceneState.scrollY);
visibleElements.forEach(element => {
context.save();
context.translate(element.x, element.y);
renderElement(element, rc, context);
context.restore();
});
context.restore();
// Pain selection element
Fix issues related to history (#701) * Separate UI from Canvas * Explicitly define history recording * ActionManager: Set syncActionState during construction instead of in every call * Add commit to history flag to necessary actions * Disable undoing during multiElement * Write custom equality function for UI component to render it only when specific props and elements change * Remove stale comments about history skipping * Stop undo/redoing when in resizing element mode * wip * correctly reset resizingElement & add undo check * Separate selection element from the rest of the array and stop redrawing the UI when dragging the selection * Remove selectionElement from local storage * Remove unnecessary readonly type casting in actionFinalize * Fix undo / redo for multi points * Fix an issue that did not update history when elements were locked * Disable committing to history for noops - deleteSelected without deleting anything - Basic selection * Use generateEntry only inside history and pass elements and appstate to history * Update component after every history resume * Remove last item from the history only if in multi mode * Resume recording when element type is not selection * ensure we prevent hotkeys only on writable elements * Remove selection clearing from history * Remove one point arrows as they are invisibly small * Remove shape of elements from local storage * Fix removing invisible element from the array * add missing history resuming cases & simplify slice * fix lint * don't regenerate elements if no elements deselected * regenerate elements array on selection * reset state.selectionElement unconditionally * Use getter instead of passing appState and scene data through functions to actions * fix import Co-authored-by: David Luzar <luzar.david@gmail.com>
2020-02-05 22:47:10 +04:00
if (selectionElement) {
context.save();
scaleContextToZoom();
translateContextToZoom();
context.translate(sceneState.scrollX, sceneState.scrollY);
context.translate(selectionElement.x, selectionElement.y);
Fix issues related to history (#701) * Separate UI from Canvas * Explicitly define history recording * ActionManager: Set syncActionState during construction instead of in every call * Add commit to history flag to necessary actions * Disable undoing during multiElement * Write custom equality function for UI component to render it only when specific props and elements change * Remove stale comments about history skipping * Stop undo/redoing when in resizing element mode * wip * correctly reset resizingElement & add undo check * Separate selection element from the rest of the array and stop redrawing the UI when dragging the selection * Remove selectionElement from local storage * Remove unnecessary readonly type casting in actionFinalize * Fix undo / redo for multi points * Fix an issue that did not update history when elements were locked * Disable committing to history for noops - deleteSelected without deleting anything - Basic selection * Use generateEntry only inside history and pass elements and appstate to history * Update component after every history resume * Remove last item from the history only if in multi mode * Resume recording when element type is not selection * ensure we prevent hotkeys only on writable elements * Remove selection clearing from history * Remove one point arrows as they are invisibly small * Remove shape of elements from local storage * Fix removing invisible element from the array * add missing history resuming cases & simplify slice * fix lint * don't regenerate elements if no elements deselected * regenerate elements array on selection * reset state.selectionElement unconditionally * Use getter instead of passing appState and scene data through functions to actions * fix import Co-authored-by: David Luzar <luzar.david@gmail.com>
2020-02-05 22:47:10 +04:00
renderElement(selectionElement, rc, context);
context.restore();
Fix issues related to history (#701) * Separate UI from Canvas * Explicitly define history recording * ActionManager: Set syncActionState during construction instead of in every call * Add commit to history flag to necessary actions * Disable undoing during multiElement * Write custom equality function for UI component to render it only when specific props and elements change * Remove stale comments about history skipping * Stop undo/redoing when in resizing element mode * wip * correctly reset resizingElement & add undo check * Separate selection element from the rest of the array and stop redrawing the UI when dragging the selection * Remove selectionElement from local storage * Remove unnecessary readonly type casting in actionFinalize * Fix undo / redo for multi points * Fix an issue that did not update history when elements were locked * Disable committing to history for noops - deleteSelected without deleting anything - Basic selection * Use generateEntry only inside history and pass elements and appstate to history * Update component after every history resume * Remove last item from the history only if in multi mode * Resume recording when element type is not selection * ensure we prevent hotkeys only on writable elements * Remove selection clearing from history * Remove one point arrows as they are invisibly small * Remove shape of elements from local storage * Fix removing invisible element from the array * add missing history resuming cases & simplify slice * fix lint * don't regenerate elements if no elements deselected * regenerate elements array on selection * reset state.selectionElement unconditionally * Use getter instead of passing appState and scene data through functions to actions * fix import Co-authored-by: David Luzar <luzar.david@gmail.com>
2020-02-05 22:47:10 +04:00
}
// Pain selected elements
if (renderSelection) {
const selectedElements = elements.filter(element => element.isSelected);
const dashledLinePadding = 4 / sceneState.zoom;
context.save();
scaleContextToZoom();
translateContextToZoom();
context.translate(sceneState.scrollX, sceneState.scrollY);
selectedElements.forEach(element => {
const [
elementX1,
elementY1,
elementX2,
2020-01-24 12:04:54 +02:00
elementY2,
] = getElementAbsoluteCoords(element);
const elementWidth = elementX2 - elementX1;
const elementHeight = elementY2 - elementY1;
const initialLineDash = context.getLineDash();
context.setLineDash([8 / sceneState.zoom, 4 / sceneState.zoom]);
context.strokeRect(
elementX1 - dashledLinePadding,
elementY1 - dashledLinePadding,
elementWidth + dashledLinePadding * 2,
elementHeight + dashledLinePadding * 2,
);
context.setLineDash(initialLineDash);
});
context.restore();
// Paint resize handlers
if (selectedElements.length === 1 && selectedElements[0].type !== "text") {
context.save();
scaleContextToZoom();
translateContextToZoom();
context.translate(sceneState.scrollX, sceneState.scrollY);
const handlers = handlerRectangles(selectedElements[0], sceneState.zoom);
Object.values(handlers)
.filter(handler => handler !== undefined)
.forEach(handler => {
context.strokeRect(handler[0], handler[1], handler[2], handler[3]);
});
context.restore();
}
}
// Paint scrollbars
if (renderScrollbars) {
const scrollBars = getScrollBars(
elements,
normalizedCanvasWidth,
normalizedCanvasHeight,
sceneState,
);
context.save();
context.fillStyle = SCROLLBAR_COLOR;
context.strokeStyle = "rgba(255,255,255,0.8)";
[scrollBars.horizontal, scrollBars.vertical].forEach(scrollBar => {
if (scrollBar) {
roundRect(
context,
scrollBar.x,
scrollBar.y,
scrollBar.width,
scrollBar.height,
2020-01-24 12:04:54 +02:00
SCROLLBAR_WIDTH / 2,
);
}
});
context.restore();
}
return visibleElements.length > 0;
}
function isVisibleElement(
element: ExcalidrawElement,
viewportWidth: number,
viewportHeight: number,
{
scrollX,
scrollY,
zoom,
}: {
scrollX: number;
scrollY: number;
zoom: number;
},
) {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
// Apply zoom
const viewportWidthWithZoom = viewportWidth / zoom;
const viewportHeightWithZoom = viewportHeight / zoom;
const viewportWidthDiff = viewportWidth - viewportWidthWithZoom;
const viewportHeightDiff = viewportHeight - viewportHeightWithZoom;
return (
x2 + scrollX - viewportWidthDiff / 2 >= 0 &&
x1 + scrollX - viewportWidthDiff / 2 <= viewportWidthWithZoom &&
y2 + scrollY - viewportHeightDiff / 2 >= 0 &&
y1 + scrollY - viewportHeightDiff / 2 <= viewportHeightWithZoom
);
}
// This should be only called for exporting purposes
export function renderSceneToSvg(
elements: readonly ExcalidrawElement[],
rsvg: RoughSVG,
svgRoot: SVGElement,
{
offsetX = 0,
offsetY = 0,
}: {
offsetX?: number;
offsetY?: number;
} = {},
) {
if (!svgRoot) {
return;
}
// render elements
elements.forEach(element => {
renderElementToSvg(
element,
rsvg,
svgRoot,
element.x + offsetX,
element.y + offsetY,
);
});
}
function getContextTransformScaleX(transform: DOMMatrix): number {
return transform.a;
}
function getContextTransformScaleY(transform: DOMMatrix): number {
return transform.d;
}
function getContextTransformTranslateX(transform: DOMMatrix): number {
return transform.e;
}
function getContextTransformTranslateY(transform: DOMMatrix): number {
return transform.f;
}