0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SVGの描画内容を表示領域にフィッティングさせる(ViewBox)

Posted at

どれだけずらせば良いかわかっている場合

<style>svg{border: 1px solid orange}</style>
  
<svg width="100" height="100">
  <circle cx="0" cy="0" r="30">
</svg>
  
<svg viewBox="-30, -30, 60, 60" width="100" height="100">
  <circle cx="0" cy="0" r="30">
</svg>

image.png

この場合はviewBoxで指定するよりも、<circle>のcx/cy属性でずらすのが普通かも

ずらす量がわからない場合

例えば、次のような場合

<svg width="200" height="70">
  <text text-anchor="start" x="40" y="20">
    Left alignment
  </text>
  <text text-anchor="end" x="40" y="50">
    Right alignment
  </txt>
</svg>

image.png

表示している内容の実サイズがわからないのでviewBoxの値を指定できない。
なので、とりあえず描画してからgetBBoxでサイズを取得してviewBoxを指定する。

<svg id="fit" width="200" height="70">
  <text text-anchor="start" x="40" y="20">
    Left alignment
  </text>
  <text text-anchor="end" x="40" y="50">
    Right alignment
  </txt>
</svg>
JavaScript
var fit = document.getElementById("fit");
var bbox = fit.getBBox();

fit.setAttribute(
  "viewBox", bbox.x + ", " + bbox.y + ", " + bbox.width + ", " + bbox.height
);

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?