How avoid SVG from scaling as its container shrinks? - svg

I want an SVG to not scale as its container shrinks. On scroll, my container shrinks its height (its width stays the same). That container contains an SVG that I want to not become scaled, but instead have its lower part become invisible/cut off.
I can do it if I (by CSS) use my SVG as a background, but I'd prefer to have the SVG inline in the HTML.
I have tried with various values for the SVG attribute preserveAspectRatio. I thought that the value xMidYMin slice would slice off the bottom part of my SVG (like I want), but it squashes its height instead.
My container is 245x80 px and on scroll is shrinked to 245x40 px.
My svg element has attribute viewBox set to 0 0 245 80 , and has no width or height explicitly defined.

You can use preserveAspectRatio="xMidYMin slice" for the svg element.
Please observe that the svg element has a viewBox and also a width and a height. While the aspect ratio of the viewBox is 1:1 the aspect ratio from width and height is 2:1
xMidYMin - Force uniform scaling.
Align the midpoint X value of the element's viewBox with the midpoint X value of the viewport.
Align the of the element's viewBox with the smallest Y value of the viewport.
slice - Scale the graphic such that:
the aspect ratio is preserved and
the entire viewport is covered by the viewBox
Please read more about preserveAspectRatio
In the next demo use the slider to change the height of the svg element
itr.addEventListener("input",()=>{svg.setAttribute("height",itr.value)})
svg{border:solid}
<p><input id="itr" type="range" min="10" max="200" value="100"/></p>
<svg preserveAspectRatio="xMidYMin slice" viewBox="0 0 100 100" width="200" height="100" id="svg">
<defs>
<path style="fill:gold; stroke:black; stroke-width: 8px;
stroke-linecap: round; stroke-linejoin: round;" id="smiley" d="M50,10 A40,40,1,1,1,50,90 A40,40,1,1,1,50,10 M30,40 Q36,35,42,40 M58,40 Q64,35,70,40 M30,60 Q50,75,70,60 Q50,75,30,60" />
</defs>
<use href="#smiley" />
</svg>

Related

Implement Zooming with viewbox in nested SVGs

I have been tasked to implement zooming in custom charts based on SVGs. Before i had one <svg> element. I looked into either using the transform or the viewbox approach and decided for the viewbox approach. Since i have to support zooming on just the x-axis, the charts contents will be squashed depending on the zoomFactor and need preserveAspectRatio="none". This does not look pretty for the chart labels that i used foreignObjects for. They get disorted as well and are not readable anymore. I did not find any solutions on how to apply the viewbox to just the actual chart contents, not the scales / labels.
I came up with the solution to split the chart into 3 nested svgs. The structure looks like this:
<svg> // Container SVG
<svg>...</svg> // XAxis
<svg>...</svg> // YAxis
<svg>...</svg> // ChartContent
</svg>
The viewbox will only be applied to the ChartContent svg and the svgs with the actual scales stay untouched and are just simply rerendered if needed with different labels at different positions. The desired outcome is similar to this example: https://jsfiddle.net/19h83ker/1/
Given that i have a chart to display that is as an example 4000 pixels wide and 200 pixels high, the y-axis is 40 pixels wide and 200 pixels high, the x-axis is 40 pixels high and 4000 pixels wide, how should i generally setup the viewports? If i set width="100%" and height="100%" on the ContainerSVG and ChartContent SVG, i have no scrollbar available. If i set width="4040" on the ContainerSVG and width="4000" on the ChartContent SVG, i have a scrollbar but applying the viewbox while zooming out by 100% will simply halve my svg in width and the right 50% are left blank. I dont really understand what the combination of widths / heights is in my structure, that i should be going for. Or am i making a mistake in general? Are there better ways to implement the desired outcome? I have already spent 2 days on this and dont really see any other option than these 3 nested svgs.At the end of the day panning / zooming in the 4000 pixel wide example SVG chart should be possible.
The suggestions you mentioned involve setting width and height, then using the default browser behavior for scroll and zoom. Instead, you need to intercept the appropriate events and modify the viewBox attribute.
The code below demonstrates zooming on mouse wheel events. Panning should be simpler (only the first and second parts of the viewBox need to change) but the implementation depends on what UI controls you want to use.
svg = document.getElementById("s")
var vb = [0,0,300,200]
svg.setAttribute("viewBox",vb) // vb gets converted to the string "0,0,300,40"
function zoom(wheelEvent){
let k=1.005**wheelEvent.deltaY
let ctm = svg.children[0].getScreenCTM()//If the svg is empty, this won't work
// position of the mouse in svg coords
let mx = (wheelEvent.clientX-ctm.e)/ctm.a
let my = (wheelEvent.clientY-ctm.f)/ctm.d
// To center the zoom on the mouse, we need:
// (mx - initialX)/initialWidth == (mx - finalX)/finalWidth
// finalX = mx - (mx - initalX)*(finalWidth/initialWidth)
vb[0] = mx-(mx-vb[0])*k
vb[1] = my-(my-vb[1])*k
vb[2] *= k
vb[3] *= k
svg.setAttribute("viewBox",vb)
wheelEvent.preventDefault() // prevent the page from scrolling
}
svg.addEventListener("wheel",zoom)
html,body,svg{
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
#s{
width: 100%;
height: 100%;
background-color: red;
}
<svg id="outer" viewBox="0 0 200 100" preserveAspectRatio="xMinYMin">
<rect x="0" y="0" width="20" height="200" />
<rect x="0" y="0" width="100%" height="20" />
<svg id="s" x="20" y="20" width="180" height="180" viewBox="0,0,300,200">
<rect x="-1000" y="-1000" width="2000" height="2000" fill="lightgray"/>
<text font-size="60" x="10" y="60" fill="blue"> hello </text>
</svg>
</svg>
If you only want scaling of the x-axis, you'll need a different value for the 'preserveAspectRatio' attribute (as well as removing the code which changes vb[1] and vb[3]).

SVG viewBox, rectangle, and polyline

The SVG attribute viewBox appears to be inconsistent. It seems it doesn't scale all SVG graphics primitives the same way. Here's a sample SVG file that has a rectangle, a circle, a polyline, and a polygon. The rectangle has been properly scaled and almost filled the viewPort (which has a width of 500 and a height of 500).
Please see the SVG code and image it produced below. As you will notice the polyline, polygon, and circle did not scale to fill the view port. They do (consistently) occupy the top-left quarter of the view port though (moved but retaining the original size). Can anyone please throw some light on what's going on with this? I will greatly appreciate your feedback.
<?xml version='1.0' encoding='utf-8'?>
<svg version='1.1' xmlns='http://www.w3.org/2000/svg'
xmlns:xlink='http://www.w3.org/1999/xlink'
height='499' width='501' viewBox='100 100 200 200'>
<g stroke='BLACK' stroke-width='5' fill='none'>
<rect x='105' y='105' width='193' height='193'/>
<polygon points="150,100 200,200 100,200" style="stroke:purple" />
<polyline points='115,180 155,127 180,180' stroke='red'/>
<circle cx='150' cy='150' r='50' stroke='green'/>
</g>
</svg>
Short answer:
The SVG attribute viewBox on the sample code does scale all SVG graphics the same way; so the smaller object representations are actually smaller objects.
Explanation:
It's useful to look at he viewBox documentation to better understand the calculations. Let's try to go through you sample code step-by-step:
the SVG viewport dimensions are set to 501 by 499 (width by height)
the viewBox attributes are set as
100 for min-x and min-y, which will act like shifting the position of the viewport before its container top and left positions (which in the image it seems like irrelevant, since you also shifted all the coordinates by 100; see my note below)
200 for width and height, which will represent 100% of the viewport size (in this case ~500px); in other words, the 200 value in any children will be mapped (scaled) into ~500px
the rect has 193 as width and height, which is nearly 200, this makes it occupy almost all of the ~500px by 500px viewport area
the other items are scaled properly, but they seem smaller because, in fact, they are smaller
e.g. the circle has r='50' which would fit an imaginary outer square of 100 by 100; 100 is 50% of 200, so it is scaled to ~250px by ~250px (250 = 50% of 500); that is why the circle seems to use 1/4 of the area
the same idea is applied to the other graphic elements.
NOTE:
I found it was easier to understand the final results if there was no shift on the viewport and on the positioning coordinates. So, removing 100 from viewBox > min-x and min-y (step 2.1 above) and from all the positioning attributes would make this code easier to understand:
<?xml version='1.0' encoding='utf-8'?>
<svg version='1.1' xmlns='http://www.w3.org/2000/svg'
xmlns:xlink='http://www.w3.org/1999/xlink'
height='499' width='501' viewBox='0 0 200 200'>
<g stroke='BLACK' stroke-width='5' fill='none'>
<rect x='5' y='5' width='193' height='193'/>
<polygon points="50,0 100,100 0,100" style="stroke:purple" />
<polyline points='15,80 55,27 80,80' stroke='red'/>
<circle cx='50' cy='50' r='50' stroke='green'/>
</g>
</svg>

SVG RECT Width and Height of 100%

I am creating an SVG element, and would like to change its background color. As per this question, and as per W3C recommendations, background-color is not a standard style for SVG, but fill must be used instead. However, fill does not work and the most common solution was to create a rect element inside the svg element and make that rect element have a width and height similar to that of the svg.
So, the following is the outcome of the suggested solution:
<svg width="300" height="200">
<rect width="300" height="200" style="fill: rgb(0, 255, 0);></rect>
</svg>
I then changed that to:
<svg width="300" height="200">
<rect width="100%" height="100%" style="fill: rgb(0, 255, 0);"></rect>
</svg>
(note that I have width and height set to 100% in my second attempt).
Now my question: even though this works, is using percentages in width and height a W3C standard? Or is it a hack?
Thanks.
is using percentages in width and height a W3C standard?
Yes. According to https://www.w3.org/TR/SVG/coords.html:
The supported length unit identifiers are: em, ex, px, pt, pc, cm, mm, in, and percentages.

how to handle SVG pixel snapping

I am trying to render two svg lines using path element.
The first line has 1px width and it is sharp
The second line has 2px width and it is blurred
The stroke-width is the same for both.
How to fix this
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<path style="stroke-width:1;stroke:red;opacity:1;" d="M 300.5 250 L 300.5 300 "></path>
<path style=" stroke-width:1;stroke:red;opacity:1;" d="M 350 250 L 350 300 "></path>
</svg>
Mainly it's the 0.5 offset that makes the line sharp. By default, integer coordinates map to the intersections of the pixel squares. So a width-1 horizontal/vertical line is centered on the boundary between pixel rows and extends half way into the pixels on either side.
So to fix the second line either add 0.5 to the co-ordinates or use the style shape-rendering: crispEdges. Note that crispEdges prevents antialiasing so horizonal/vertical lines are crisp but angled lines look blocky.
Also stroke-width=1 is not valid CSS syntax. The first example stroke-width: 1 has it right.
Just Try to move the SVG element.
svg {
padding: .5px;
}

How does setting viewBox attribute, affects the user coordinates

I have the following code: http://jsfiddle.net/fCWJ5/1/, and following doubts regarding the viewbox.
body{margin:0;}
#test{width:200px;height:200px;border:solid red 1px;}
<body>
<div id="test">
<!-- preserveAspectRatio="xMinYMin meet" -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 150"
xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full">
<g>
<rect class="drag resize" x="150" y="50" width="50" height="50" fill="#c66" />
</g>
</svg>
</div>
</body>
From the fiddle one user coordinate = .2, this I got by dividing
200/1000 (test div width / viewBox width attribute). According to
this, the rectangle should be at (30px, 10px), with a width and
height of 10px, 10px respectively. But the rectangle is at
(30px,97px), with a width and height of 10px,10px (some how height
and width is correct as per calculation.). Please point out why the
y coordinate is wrong.
Then I gave preserveAspectRatio="xMinYMin meet" as said in a svg
tutorial pdf. It was working fine for this value. But for other
value the display goes for toss. Please explain what is this. I
already asked a question regarding this
could not able to put viewbox,viewport,userspace together and get the picture.
I'm unable to understand the answer and the concept.
what will be the value of the ratio, if I didn't specified any width
and height for the svg dom element container.
I'm seeing that the ratio 1.3, (height of the test div/height
attribute of the viewBox), is not used. Should that be used for
calculating things like height,y coordinates.
The problem is the aspect ratio of your DIV does not match the aspect ratio of your viewBox. So HTML puts your SVG in the center of the DIV with the empty space above and below. Add the following to your SVG code to illustrate:
<rect x="0" y="0" width="100%" height="100%" fill="none" stroke="black"/>
This will show you the boundaries of your SVG element, while the red border you put on your DIV will show you its boundary. They don't match.
If you don't put a width or height on the SVG element then it will fill its container. In your example you set the DIV to 200px X 200px, the viewBox will then be applied effectively dividing the 200px by 1000 user units for X and 30px by 150 for the Y (because of the aspect ratio of the SVG only 15% of the DIV height is used by the SVG, 15% of 200px is 30px). Remove the width and height from the DIV and it will use the full width of the screen.
If you add my rect element you will see that your box is 1/3 (50/150 = 1/3) from the top extending 1/3 down, while also being 3/20 (150/1000 = 3/20) in from the left and extending 1/20 (50/1000 = 1/20) across.

Resources