1
1

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 1 year has passed since last update.

SVGSVGElement

Last updated at Posted at 2014-03-04

SVG要素を表すDOMオブジェクトにSVGSVGElementがあります。
取得する方法は、ownerDocumentのdocumentElementを取得する方法と、
各要素のownerSVGElementから取得する方法があります。

(下記の例では、evt.targetがそもそもSVGSVGElementですが、あえて別な方法で取得しています。)

svgsvgelement.svg
<svg xmlns="http://www.w3.org/2000/svg" onload="func(evt)">
<script><![CDATA[
function func(evt) {
    var ns = "http://www.w3.org/2000/svg";
    var doc = evt.target.ownerDocument;
    alert(doc.documentElement); //documentElementから取得する方法
    alert(doc.getElementById("r1").ownerSVGElement);  //ownerDocumentから取得する方法
}
]]></script>
<rect id="r1" x="10" y="10" width="100" height="100" fill="red" />
</svg>

SVGSVGElementはいろんな情報をもっており、
またいそんなメソッドが用意されています。

たとえば、pauseAnimation()でアニメーションを停止し、unpauseAnimation()でアニメーションを再会できます。

animation.svg
<svg xmlns="http://www.w3.org/2000/svg">
<script><![CDATA[
function pause(evt) {
    var svg = evt.target.ownerSVGElement;
    svg.pauseAnimations();
}

function unpause(evt) {
    var svg = evt.target.ownerSVGElement;
    svg.unpauseAnimations();
}
]]></script>
<rect id="r1" x="10" y="10" width="100" height="100" fill="red">
  <animate attributeType="XML" attributeName="x"
           from="10" to="100" dur="10s" />
</rect>
<rect id="r2" x="10" y="110" width="20" height="20" fill="blue" onclick="pause(evt)" />
<rect id="r3" x="40" y="110" width="20" height="20" fill="blue" onclick="unpause(evt)" />
</svg>

下の青の矩形の左はアニメーションを停止、右はアニメーションを再会させます。

またsetCurrentTimeで現在の時間を秒数で指定できます。
下記の例は青の矩形をクリックするたびにアニメーションの2秒後の状態から再生されます。
アニメーションが終わっても、時間が戻ってしまって、開始から2秒後の時点からのアニメーションになります。

animation2.svg
<svg xmlns="http://www.w3.org/2000/svg">
<script><![CDATA[
function func(evt) {
    var svg = evt.target.ownerSVGElement;
    svg.setCurrentTime(2);
}

]]></script>
<rect id="r1" x="10" y="10" width="100" height="100" fill="red">
  <animate attributeType="XML" attributeName="x"
           from="10" to="100" dur="10s" />
</rect>
<rect id="r2" x="10" y="110" width="20" height="20" fill="blue" onclick="func(evt)" />
</svg>
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?