Search code examples
javascriptjquerycsssvgsnap.svg

make svg snap image line up on a div


Here is the code. The svg is 1279 x 859.

How do I get the graphic to align its top-left corner to the Right now it lines up on the top-left corner of the browser's tab/window.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
    <style type="text/css">
        svg { position:fixed; top:0; left:0; height:100%; width:100%;
    }
    </style>

    <script src="/script/jquery-1.10.2.min.js" type="text/javascript"></script>



    <script src="/script/snap.svg.js" type="text/javascript"></script>
    <script src="/script/snap.svg.zpd.js" type="text/javascript"></script>

    <div id="jqxPanel" style="padding: 20px; border:1px solid black; width: 1920px; height: 1080px">
        <div id="image" style="padding: 2px; border: 1px solid black"; width: 1290px; height: 870px">
            <svg id="SnapCanvas" ></svg>
        </div>
    </div>

    <script type="text/javascript">
        var BaseSVG = Snap('#SnapCanvas');
        $(document).ready(function () {

            SVGElement.prototype.getTransformToElement = SVGElement.prototype.getTransformToElement || function (elem) {
                return elem.getScreenCTM().inverse().multiply(this.getScreenCTM());
            }

            Snap.load("Canvas.svg", function (f) {
                BaseSVG.append(f);
            });

        });
    </script>   
</body>
</html>

Solution

  • A) You're missing some words from your questions. I'm assuming you mean to say, "How do I get the graphic to align its top-left corner to the top left corner of its container"

    If so,

    B)Your image has:

    position: fixed;
    

    Fixed positioning means that the element will measure its top, bottom, left, right values from the edge of the viewport (i.e. the window). What you want is:

    position: absolute;
    

    Positioning something absolutely means that its top, bottom, left, and right values will be measured from the edges of its last positioned ancestor. That part is important. None of it's ancestor elements are positioned by default. All elements have position: static by default. static is the only value for the position property that is not considered positioned. So, you need to change the position property of the svg's parent. I would change it to relative because it's least likely to screw with your styles.

    At the end of the day your styles should look like this:

     svg { 
       position:absolute; 
       top:0; 
       left:0; 
       height:100%; 
       width:100%;
     }
    
     #image {
       position: relative;
     }
    

    Edited for typos.