John Smith
John Smith

Reputation: 313

svg - flip upside down ex. graph

I'm trying to work out a simple svg example - creating bar graph. However, I don't have clear grasp of how it works. I rotated an existing graph upside down but seems like there is a small offset. Corresponding jsfiddle here - http://jsfiddle.net/rhvP8/2/

  <div style="width:300px;height:300px;">
  <svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:100%;height:100%" viewBox="0 0 300 300">
    <g>
        <rect  width="14.55" height="40%" x="0" y="0" fill="black"></rect>
        <rect  width="14.55" height="20%" x="50" y="0" fill="green"></rect>
        <rect  width="14.55" height="80%" x="100" y="0" fill="red"></rect>
        <rect  width="14.55" height="90%" x="150" y="0" fill="yellow"></rect>
        <rect  width="14.55" height="10%" x="200" y="0" fill="pink"></rect>
        <rect  width="14.55" height="60%" x="250" y="0" fill="orange"></rect>
    </g>
</svg> 
</div>
<div style="width:300px;height:300px;">
 <svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:100%;height:100%" viewBox="0 0 300 300">
    <g transform="rotate(180)">
        <rect  width="14.55" height="40" x="-50" y="-300" fill="black"></rect>
        <rect  width="14.55" height="20" x="-100" y="-300" fill="green"></rect>
        <rect  width="14.55" height="35" x="-150" y="-300" fill="red"></rect>
        <rect  width="14.55" height="90" x="-200" y="-300" fill="yellow"></rect>
        <rect  width="14.55" height="10" x="-250" y="-300" fill="pink"></rect>
        <rect  width="14.55" height="60" x="-300" y="-300" fill="orange"></rect>
    </g>
    </svg> 
</div>

Upvotes: 0

Views: 4210

Answers (3)

ByREV
ByREV

Reputation: 31

Easy way: the scaleY() CSS function, defines a transformation that resizes an element along the y-axis (vertically).

svg {
  transform: scaleY(-1);
}

View browser compatibility here: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scaleY()#browser_compatibility

Upvotes: 0

Paul LeBeau
Paul LeBeau

Reputation: 101956

An alternative to squeamish's solution is just to use the version of rotate that takes the rotation origin as well: rotate(angle x y).

Since you know your graph is 300x300, using rotate(180 150 150) works fine.

Demo here

Upvotes: 1

r3mainer
r3mainer

Reputation: 24587

The thing you need to remember is that the rotate() transform will rotate an object about the coordinates (0,0), which in this case is the top left corner of the graph. Since the graph is 300p wide and 300px tall, rotating through 180° causes the graph to spin off beyond the top left corner. A translate transform can be used to readjust the coordinates so that the drawing appears within the viewbox again. Hopefully this illustration will explain:

Illustration of rotate and translate transforms in an SVG

Here's an updated JSfiddle with a few other fixes: http://jsfiddle.net/rhvP8/4/

Upvotes: 1

Related Questions