@zohodesk/a11y
Version:
In this Package, We Provide Some Basic Components For Accessibility.
90 lines (77 loc) • 2.61 kB
JavaScript
import { useCallback, useMemo } from 'react';
import { alphaColor, globalCompositeOperation } from '../data/constants';
export default function useDrawShape(_ref) {
let {
canvasState,
alpha,
lastMousePosition,
canvasContext,
getRootElement
} = _ref;
// Memoize the dimensions to avoid recalculating on every render
const {
width,
height,
rectangleWidth,
rectangleHeight
} = useMemo(() => canvasState, [canvasState]);
function setAlphaForReadingMask(_ref2) {
let {
alpha,
color,
width,
height
} = _ref2;
// Apply alpha and compositing
canvasContext.current.globalAlpha = alpha;
canvasContext.current.globalCompositeOperation = globalCompositeOperation;
canvasContext.current.fillStyle = color;
canvasContext.current.fillRect(0, 0, width, height);
}
const drawRectangle = useCallback(function () {
let {
mouseX = lastMousePosition.current.lastMouseX,
mouseY = lastMousePosition.current.lastMouseY,
type = '',
iframeData
} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// If no canvas context, return early
lastMousePosition.current.lastMouseX = mouseX;
lastMousePosition.current.lastMouseY = mouseY;
if (canvasContext && canvasContext.current) {
canvasContext.current.clearRect(0, 0, width, height);
setAlphaForReadingMask({
alpha,
color: alphaColor,
width,
height
});
const centerX = rectangleWidth / 2;
const centerY = rectangleHeight / 2;
if (type == 'iframe') {
mouseX = mouseX + iframeData.x;
mouseY = mouseY + iframeData.y;
}
if (getRootElement()) {
mouseX = mouseX - getRootElement().getBoundingClientRect().x;
mouseY = mouseY - getRootElement().getBoundingClientRect().y;
} // Calculate position, restricting it within the canvas borders
let x = Math.max(mouseX - centerX, 0);
let y = Math.max(mouseY - centerY, 0); // Adjust if rectangle overflows the canvas boundaries
const overflowX = x + rectangleWidth - width;
const overflowY = y + rectangleHeight - height;
if (overflowX > 0) {
x -= overflowX;
}
;
if (overflowY > 0) {
y -= overflowY;
}
; // Clear the specific rectangle area
canvasContext.current.clearRect(x, y, rectangleWidth, rectangleHeight);
}
}, [alpha, width, height, rectangleWidth, rectangleHeight, lastMousePosition, canvasContext, getRootElement]);
return {
drawRectangle
};
}