I’ve added resize and Moving of Elements to my Canvas along with the functionality to lock/ select certain elements( since my select Elements automatically selects the first drawn element).
For Some Odd Reason, I’m unable to move Some elements( i am able to resize them), this happens when i have more than 25 elements on canvas, even though none of them are locked / highlighted i cannot move some elements
Website Link : Canvas
Github Link : GitHub
const [toolType, setToolType] = useState<string>("rectangle");
const [elementType, setElementType] = useState<string>("normal");
const [action, setAction] = useState<string>("none");
const [dottedLine, setDottedLine] = useState(false);
const [dotLineSize, setDotLineSize] = useState(5);
const [dottedCanvas, setDottedCanvas] = useState(true);
const [highLightedElement, setHighLightedElement] = useState<element | null>(null);
type element = {
toolType: string;
elementType: string;
id: number;
x1: number;
y1: number;
x2: number;
y2: number;
locked: boolean;
dotLinesize: number;
position?: string;
};
// TODO remove this Element and replace it with Element
interface Positionelement {
position: string | null;
toolType: string;
elementType: string;
id: number;
x1: number;
y1: number;
x2: number;
y2: number;
locked: boolean;
dotLinesize: number;
}
My OnMouseDown function:
const closestPoint = (
x: number,
y: number,
x1: number,
y1: number,
name: string
): string | null => {
return Math.abs(x - x1) < 20 && Math.abs(y - y1) < 20 ? name : null;
};
const distance = (
a: { x: number; y: number },
b: { x: number; y: number }
): number => {
return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
};
const PositionWithinElement = (x: number, y: number, element: element) => {
if (element.locked) return null;
const { x1, x2, y1, y2, toolType } = element;
if (toolType === "line") {
const a = { x: x1, y: y1 };
const b = { x: x2, y: y2 };
const c = { x: x, y: y };
const offset = distance(a, b) - (distance(a, c) + distance(b, c));
const start = closestPoint(x, y, x1, y1, "start");
const end = closestPoint(x, y, x2, y2, "end");
const inside = Math.abs(offset) < 1 ? "inside" : null;
return start || end || inside;
}
if (toolType === "rectangle") {
const TopLeft = closestPoint(x, y, x1, y1, "tl");
const TopRight = closestPoint(x, y, x2, y1, "tr");
const BottomLeft = closestPoint(x, y, x1, y2, "bl");
const BottomRight = closestPoint(x, y, x2, y2, "br");
const inside = x <= x2 && y <= y2 && x >= x1 && y >= y1 ? "inside" : null;
return TopLeft || TopRight || BottomLeft || BottomRight || inside;
}
return null;
};
const getElementAtPosition = (
x: number,
y: number,
elements: element[]
): Positionelement | null => {
return (
elements
.map((el) => ({ ...el, position: PositionWithinElement(x, y, el) }))
.find((el) => el.position != null) || null
);
};
const handleMouseDown = (event: React.MouseEvent<HTMLCanvasElement>) => {
const { clientX, clientY } = event;
let currentElement;
if (toolType === "select") {
currentElement = getElementAtPosition(clientX, clientY, elements); // set a position Element
if (highLightedElement) {
//do something
// check if cursor is inside the highlighted element
//DONE: but problem arises as element has a type Element where as highlighted Element has a type of positionElement
//DONE: solution could be to remove the position from the highlighted Element and update it further down as we set it to the selected element
const el = {
...highLightedElement,
position: PositionWithinElement(clientX, clientY, highLightedElement),
};
if (el.position != null) {
currentElement = el; // if cursor inside highlighted element update it
}
}
// in the case there is no highlighted element fuction dosent invocate
if (currentElement && !currentElement.locked) {
if (currentElement.position === "inside") {
setAction("moving");
setSelectedElementOffset({
offsetX: clientX - currentElement.x1,
offsetY: clientY - currentElement.y1,
});
} else {
setAction("resize");
setSelectedElementOffset({ offsetX: 0, offsetY: 0 });
}
setSelectedElement(currentElement);
}
}
if (toolType === "line" || toolType === "rectangle") {
// @TODO : need to change this when adding resize and other options :(
setElements((prev) => [
...prev,
{
toolType: toolType,
elementType: elementType,
x1: clientX,
y1: clientY,
x2: clientX,
y2: clientY,
locked: false,
id: elements.length,
dotLinesize: dottedLine ? dotLineSize : 0,
},
]);
setAction("drawing");
}
};
My Mouse Move And Mouse Up Functions:
const handleMouseMove = (event: React.MouseEvent<HTMLCanvasElement>) => {
const { clientX, clientY } = event;
if (action === "moving" && selectedElement) {
const { offsetX, offsetY } = selectedElementOffset;
const width = selectedElement.x2 - selectedElement.x1;
const height = selectedElement.y2 - selectedElement.y1;
const newX1 = clientX - offsetX;
const newY1 = clientY - offsetY;
const updatedElement = {
...selectedElement,
x1: newX1,
y1: newY1,
x2: newX1 + width,
y2: newY1 + height,
};
setSelectedElement(updatedElement);
updateElement(
selectedElement.id,
newX1,
newY1,
newX1 + width,
newY1 + height,
selectedElement.toolType,
selectedElement.elementType,
selectedElement.dotLinesize
);
}
if (toolType === "select") {
const element = getElementAtPosition(clientX, clientY, elements);
(event.target as HTMLCanvasElement).style.cursor = element
? CursorIcon(element.position)
: "default";
}
if (action === "resize" && selectedElement) {
const { x1, y1, x2, y2 } = ResizeElement(
selectedElement.x1,
selectedElement.y1,
selectedElement.x2,
selectedElement.y2,
selectedElement.position,
clientX,
clientY
);
updateElement(
selectedElement.id,
x1,
y1,
x2,
y2,
selectedElement.toolType,
selectedElement.elementType,
selectedElement.dotLinesize
);
}
if (action === "drawing") {
setElements((prev) => {
const updatedElements = [...prev];
const length = updatedElements.length;
if (length > 0) {
const element = updatedElements[length - 1];
updateElement(
element.id,
element.x1,
element.y1,
clientX,
clientY,
element.toolType,
element.elementType,
element.dotLinesize
);
}
return updatedElements;
});
}
};
const adjustElementCoordinates = (el: element) => {
const { x1, y1, x2, y2, toolType } = el;
if (toolType === "rectangle") {
const minX = Math.min(x1, x2);
const minY = Math.min(y1, y2);
const maxX = Math.max(x1, x2);
const maxY = Math.max(y1, y2);
return { x1: minX, y1: minY, x2: maxX, y2: maxY };
}
if (toolType === "line") {
if (x1 < x2 || (x1 === x2 && y1 < y2)) {
return { x1, y1, x2, y2 };
} else {
return { x1: x2, y1: y2, x2: x1, y2: y1 };
}
}
return null;
};
const handleMouseUp = (event: React.MouseEvent<HTMLCanvasElement>) => {
(event.target as HTMLCanvasElement).style.cursor = "default";
const index = elements.length - 1;
if (action === "drawing") {
const element = elements[index];
const adjustedCoordinates = adjustElementCoordinates(element);
if (adjustedCoordinates) {
const { x1, y1, x2, y2 } = adjustedCoordinates;
updateElement(
element.id,
x1,
y1,
x2,
y2,
element.toolType,
element.elementType,
element.dotLinesize
);
}
}
setAction("none");
setSelectedElement(null);
setHighLightedElement(null);
};
My Code Which allows me to select a certain Element from the canvas:
<ul className="w-full m-2">
{elements.map((element) => (
<>
<li
key={element.id}
className={`cursor-pointer w-full flex items-center gap-2 my-2 px-2 capitalize h-6 justify-between group ${
highLightedElement?.id === element.id ? "bg-gray-200" : ""
}`}
onClick={() => {
if (!element.locked) {
setToolType("select");
setHighLightedElement(element);
setAction("selected");
}
}}
>
<div className="flex items-center h-full text-baseline text-sm noselect">
{getIcon(element.toolType, element.dotLinesize)}
{element.elementType}
{element.toolType} {element.id + 1}
</div>
<div
className="none group-hover:block"
onClick={() => {
toggleLock(element.id);
}}
>
{element.locked ? (
<CiLock className="w-6 h-6" />
) : (
<CiUnlock className="w-6 h-6" />
)}
</div>
</li>
<hr />
</>
))}
</ul>
I was trying to imitate the lock and selection of elements from the popular site Figma. I haven’t implemented layering yet so i made a highlightedElement State instead to act as a lever for me to select and move elements layered on top of each other, along with the ability for me to lock elements at their places in order for them not to move/resize from their said position.