0

I tried to transform the SVG element with perspective and discovered that it does not work, but the same transformations to HTML tags work correctly.

Experiment on jsfiddle: https://jsfiddle.net/5ms7ubck/ (html transformation (red element) VS svg (gray)).

.outer {
  perspective: 1000px;
}

.inner {
  transform: rotateX(60deg) perspective(1000px);
  transform-style: preserve-3d;
  transform-origin: 50% 50%;
}
<svg width="151px" height="151px" viewBox="0 0 151 151" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <defs></defs>
      <g class="outer" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
          <rect class="inner" width="150" height="150" fill="#D8D8D8"></rect>
      </g>
</svg>

I would like to find the right way to transform SVG elements. I also tested an example from SVG Rotation in 3D and it isn't working too.

leonheess
  • 16,068
  • 14
  • 77
  • 112
  • perspective should be applied before rotation (order is important) related: https://stackoverflow.com/a/51891547/8620333 – Temani Afif Jun 10 '19 at 19:54
  • Hello! Result: https://jsfiddle.net/5ms7ubck/1/ it is still doesn't work... – Aleksandr Gorin Jun 10 '19 at 20:42
  • it somehow worked (you have to enable the overflow): https://jsfiddle.net/L5mdh7ng/ but I don't exactly know how the calculation is done with the SVG element. The perspective seems to be different – Temani Afif Jun 10 '19 at 20:47

1 Answers1

1

Some browsers, like Firefox, have support for 3D transforms on SVG shapes. For example all you have to do to get your first fiddle working if Firefox is add overflow: visible to the <svg> element.

https://jsfiddle.net/gqsy14be/ (Firefox only)

However this is an experimental feature, and right now you can't rely on cross-browser support.

But the good news is that outer <svg> elements are treated like any other HTML element and can have 3D transforms.

.test {
  display: block;
  width: 100px;
  margin: 20px;
}

.outer {
  perspective: 1000px;
}


.inner {
  transform: rotateX(60deg);
  transform-style: preserve-3d;
  transform-origin: 50% 50%;
}
<div class="test">
  <div class="outer">
    <svg width="151px" height="151px" viewBox="0 0 151 151" class="inner">
      <defs></defs>
      <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
          <rect width="150" height="150" fill="#D8D8D8"></rect>
      </g>
    </svg>
  </div>
</div>

<div class="test">
  <div class="outer">
    <div class="inner" style="background-color: red; width: 150px; height: 150px;">

    </div>
  </div>
</div>

But obviously this isn't helpful to you are trying to make 3D solids in your SVG. You can only transform the plane of the SVG.

Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181