在父SVG中居中SVG图像

时间:2016-10-12 22:24:58

标签: javascript html svg

我正在使用以下代码准备HTML / CSS / Javascript中的演示文稿。我想要的是将SVG图像置于主SVG中心。据我所知,主SVG的viewBox建立了一个新的坐标系。因此,当我尝试使用其宽度的一半(类似于“text-anchor =”middle“”)使图像居中时,我没有得到我所期望的,图像被移动但不足以位于中心。

<!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>

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。我刚刚将图像x =“0”更改为image =“ - 50%”并删除了D3选择

相关问题