I have written these functions to center one svg element in another:
import { Matrix, translate } from 'transformation-matrix';
export const getElementCenter = (element: SVGGraphicsElement) => {
const bBox = element.getBBox();
return { x: bBox.x + bBox.width / 2, y: bBox.y + bBox.height / 2 };
};
export const centerElementInOther = (
element: SVGGraphicsElement,
other: SVGGraphicsElement,
scaleFactor: number = 1
): Matrix => {
const elementCentre = getElementCenter(element);
const otherCentre = getElementCenter(other);
const x = elementCentre.x - otherCentre.x;
const y = elementCentre.y - otherCentre.y;
// how can I work out the scaleFactor? If it the actual scale is 0.5 then I need to divide by 2 but if it is 1 then I need to divide by 1
return translate(-x / scaleFactor, -y / scaleFactor);
};
Everything works unless the element is scaled then I need to apply some maths but I do not understand the ration.
Everything worked fine until I changed the scale of the element to 0.5 and then I had to divide the center x and center y by 2.