简体   繁体   中英

Centering SVG image inside parent SVG

I am preparing a presentation in HTML/CSS/Javascript using the following code. What I want is to centre an SVG image in the main SVG. From what I understand, the viewBox of the main SVG establishes a new coordinate system. So, when I try to centre the image using the half of its width (similar to "text-anchor="middle"") I do not get what I expect, the image is shifted but not enough to be in the centre.

<!doctype html>
<meta charset="utf-8">

<script src="./js/d3.js"></script>

<style>

body {
  margin:0;
  /*border: 5px solid green; /*for testing*/
  display:block;
  padding-top: 0px;
  height: 100vh;
  background-color: rgba(0,0,0,1);
  font-family: Helvetica;
}

body svg {
  /*border: 1px solid #C1543D;*/ /*for testing*/
  display:block;
  margin: auto;
}

.slideBackground {
  fill: white;
}

.slideHeader{
  font-size: 38;
}

</style>



<body>


  <svg width="100%" height="100%" viewBox="0 0 1024 768"> <!-- 1024 and 768 are expressed in units of the SVG's viewport (NOT pixels)-->

    <rect class="slideBackground" x="0%" y="0%" width="100%" height="100%"/> <!-- rect for viewbox-->

    <g id="equation">
      <svg x="50%" y="70%" width="30%" height="6%" viewBox="0 0 35 5" preserveAspectRatio="xMidYMid">
        <image x="0" y="0" width="100%" height="100%" xlink:href="bayesTheorem.svg"></image>
      </svg>
    </g>

  </svg>

</body>

<script>

var eqSVG = document.getElementById("equation");
var rec = eqSVG.getBoundingClientRect().width;

d3.select("#equation").attr("transform", "translate(" + (-rec/2) + ",0)")

</script>

I fixed the issue. I just changed image x="0" to image="-50%" and removed the D3 selection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM