UNPKG

@zohodesk/a11y

Version:

In this Package, We Provide Some Basic Components For Accessibility.

49 lines (44 loc) 1.61 kB
import { useState, useCallback, useRef } from 'react'; export default function useReadingMaskCanvas(_ref) { let { getRootElement } = _ref; const [canvasState, setCanvasState] = useState({}); const canvasRef = useRef(null); const canvasContext = useRef(null); const lastMousePosition = useRef({ lastMouseX: null, lastMouseY: null }); // Memoize the calculation of canvas dimensions and rectangle size const updateCanvasState = useCallback(function (dimensions) { let iframeData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; const width = getRootElement() ? getRootElement().offsetWidth : window.innerWidth; const height = getRootElement() ? getRootElement().offsetHeight : window.innerHeight; if (!lastMousePosition.current.lastMouseX || !lastMousePosition.current.lastMouseX) { // Set initial mouse position as center for the initial draw lastMousePosition.current.lastMouseX = width / 2; lastMousePosition.current.lastMouseY = height / 2; } setCanvasState({ height, width, rectangleWidth: dimensions.width * width / 100, rectangleHeight: dimensions.height * height / 100 }); }, []); // Memoize the canvas reference callback const getCanvasRef = useCallback(ref => { canvasRef.current = ref; if (canvasRef.current) { canvasContext.current = canvasRef.current.getContext('2d'); } else { canvasContext.current = null; } }, []); return { updateCanvasState, getCanvasRef, canvasState, canvasContext, lastMousePosition }; }