Search code examples
jquerysvgjquery-svg

Zoom to an element - jquery SVG


Say I have a canvas with svg elements drawn on it. Once i click on the element, i need to change the viewport by zooming and focusing on the element clicked. How do i perform this? I have attached the code.

`

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <title>jQuery SVG</title>
        <style type="text/css">
            #svgbasics 
            { 
                width: 1250px; 
                height: 500px; 
                border: 1px solid black; 
            }
        </style>
        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript" src="js/jquery.svg.js"></script>
        <script type="text/javascript">
            var selectedItem="";
            $(function() 
            {
                $('#viewport').svg({onLoad: drawInitial});
            });
            function drawInitial(svg) 
            {
                svg.circle(75, 75, 50, {onclick: "clickListener()",fill: 'none', stroke: 'red', 'stroke-width': 3});
                var g = svg.group({onclick: "select(evt)",stroke: 'black', 'stroke-width': 2});
                svg.line(g, 15, 75, 135, 75,{onclick: "select(evt)"});
                svg.line(g, 75, 15, 75, 135,{onclick: "select(evt)"});
            }
            function clickListener()
            {
                //code to change the viewport to this element
            }
            </script>
    </head>
    <body>
        <h1>jQuery SVG</h1>
        <div id="svgbasics" tabindex="0" onclick="this.focus()">
            <g id="viewport">
                <input type="button" value="Click me" onclick="clickListener()"/>
            </g>
        </div>
        <p>

        </p>

    </body>
</html>

`


Solution

  • Thanks. Implemented using this :

    var b = event.target.getBBox(); 
    var svg = document.getElementById('svgcanvas'); 
    svg.setAttribute("viewBox", b.x+" "+b.y+" "+b.width+" "+b.height);