Getting bounding box of elements in SVG.js

Behrang Saeedzadeh 19 October 2018

Here is a sample code that shows how to get the bounding box of elements that are added to an SVG container using the SVG.js library:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">    
    <style>
        body {
            margin: 50px;
        }

        #sheet {
            border: 1px solid black;
            box-sizing: border-box;
            width: 1024px;
            height: 768px;
        }
    </style>
    <title>SVG.js :: Get by element ID</title>
</head>
<body>    
    <div id="sheet"></div>    
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js" integrity="sha256-M8IkAPnXdVChgPQwts/KeepRP4ogs+hzBtPmVhUj5YA=" crossorigin="anonymous"></script>
    <script>
        let texts = [
            "Lorem ipsum dolor",
            "consectetur adipiscing elit",
            "ea commodo consequat"
        ];

        $(() => {    
            const sheet = SVG('sheet').size(1022, 766);
            const textSymbols =  texts.map((text) => {
                return sheet.symbol().text(text);
            });

            textSymbols.forEach((symbol, index) => {
                sheet.use(symbol).id(`index-${index}`).move(50 + index * 11, 100 + index * 31);
            });

            textSymbols.forEach((_, index) => {
                console.log(`Bounding box for 'index-${index}' => `, SVG.get(`index-${index}`).bbox());
            });
        });
    </script>
</body>
</html>

I was expecting the sheet object to have a method for accessing its children by id, but apparently I have to use the global SVG object instead:

SVG.get('the element id').bbox());

Dies ist ein wenig kontraintuitiv.