几何在前端边界计算中的应用及原理分析(一)
The following is the code for generating a rectangle: const generateRectangleMeta = (startPos: [number, number], w: number, h: number) => { if (startPos && Array.isArray(startPos) && startPos.length >= 2 && typeof w === "number" && typeof h === "number") { const [a0, b0] = startPos; const a1 = a0 + w; const b1 = b0 + h; return { startPos, w, h, endPos: [a1, b1], pos: [ [a0, b0], [a1, b0], [a1, b1], [a0, b1] ], }; } else { throw new Error("Please pass in the correct parameters"); } }; After generating the rectangle, we can draw a rectangle at any position. The next step is to get the coordinates of any point, in this case, we will use the mouse pointer as the point (x, y), and then construct a canvas: const cardOffset = ref({ x: 0, y: 0 }); onMounted(() => { // Get the distance from the left upper corner of the canvas to the left upper corner of the page const { offsetTop, offsetLeft } = document.querySelector("#boundCard") as HTMLElement; cardOffset.value.x = offsetLeft; cardOffset.value.y = offsetTop; }); const { x, y } = useMouse(window, (x, y) => { // Calculate the boundary const { x: x0, y: y0 } = cardOffset.value; const dotX = x - x0; const dotY = y - y0; const { startPos, endPos } = rectangle; if (startPos[0] <= dotX && endPos[0] >= dotX && startPos[1] <= dotY && endPos[1] >= dotY) { return true; } else { return false; } }); The following is the code for calculating the boundary of a rectangle: const calculateRectangleBoundary = (rectangle: Rectangle) => { const { startPos, endPos } = rectangle; if (startPos[0] <= dotX && endPos[0] >= dotX && startPos[1] <= dotY && endPos[1] >= dotY) { return true; } else { return false; } };
内容来源: MrXujiang/h5-Dooring