I am dynamically generating some SVG. What I want to do is divide the page in half (no matter what size it is) and be able to insert some objects on the left side of the screen and some objects on the right of the screen. I just can’t seem to get it right. I have actually tried to do it many different ways, the code listed here was my most recent attempt:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%">
<script type="text/ecmascript">
var svgNS = "http://www.w3.org/2000/svg";
var xlinkNS = "http://www.w3.org/1999/xlink";
var i = 0;
function makeBox() {
i++;
var newRect = document.createElementNS(svgNS,"rect");
newRect.setAttributeNS(null,"width", 100);
newRect.setAttributeNS(null,"height", 100);
newRect.setAttributeNS(null, "x", 10);
newRect.setAttributeNS(null, "y", i * 100);
newRect.setAttributeNS(null,"fill","blue");
if(i % 2 === 1) {
document.getElementById("screenLeft").appendChild(newRect);
} else {
document.getElementById("screenRight").appendChild(newRect);
}
}
</script>
<g id="firstGroup">
<text x="20" y="30" onclick="makeBox()" font-size="+13px">Click this text to Draw a Box.</text>
</g>
<svg id="screenLeft" viewBox="50% 100%">
</svg>
<svg id="screenRight" viewBox="50% 100%" x="50%">
</svg>
</svg>
Of course I changed a bunch of code to make this post more concise. What it does is, when user clicks the text, it draws a rectangle in element “screenLeft” or “screenRight” depending on if the increment (i) is even or odd.
The way I have the viewBox setup right now sort of works. If I reduce the chrome window to a smaller size, the gap between the “leftSide” and the “rightSide” does get smaller. However, if I have the window Maximized, the screen area is WAY too big. I have to scroll far to the right to see the “rightSide”. It is about twice my screen size.
I have also tried several other methods, involving grouping.
So, I guess my question is, what is the best way to divide the screen in half so I can generate some objects on the left side of the screen and some on the right side of the screen, while allowing the total screen size to differ?
Give your
<svg>element aviewBoxwith fixed width and an exceptional height. Then specify apreserveAspectRatioattribute with the value ofxMidYMid slice.This will ensure that the full width of your SVG viewport will always cover the viewBox, and half of your viewBox will thus cover half the screen.
See this live: http://phrogz.net/svg/half-width.svg
The only downside with this (which I can’t tell if it matters to you) is that resizing the browser window will resize the elements. Maybe you want elements to always remain the same size on screen no mater how large the browser?