LoginSignup
30
25

More than 5 years have passed since last update.

SVG に JavaScript を埋め込む方法

Last updated at Posted at 2013-06-14

SVG は内部に JavaScript を埋め込むことができる。

SVG ファイル内への JavaScript の記述例

以下の SVG をブラウザで開くと埋め込んだ JavaScript が実行される(Safari, Chrome で確認)。
表示されている図形をクリックするとランダムに色が変わる。

with_js.svg
<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" version="1.1" width="400pt" height="400pt">
  <script><![CDATA[
    function fillRandomColor(e) {
        var r = Math.floor(Math.random() * 255.0);
        var g = Math.floor(Math.random() * 255.0);
        var b = Math.floor(Math.random() * 255.0);
        e.setAttribute('fill', 'rgb(' + r + ', ' + g + ', ' + b + ')');
    }
  ]]></script>
  <rect id="r1" x="10" y="10" width="200" height="100" stroke="blue" fill="yellow" onclick="fillRandomColor(this);" />
</svg>

HTML における JavaScript とはいくつか違いがある模様。

  • SVG の読み込み完了は window.onload の代わりに document.documentElement.onload を使う。
  • jQuery は基本的に使えない(HTML DOM を前提としたライブラリは使用不可)。

HTML で SVG ファイルを参照するとき

HTML 中から SVG ファイルを参照する方法は 2 つある。

  • img タグを使う
  • object タグを使う

img タグを使って参照した場合は JavaScript が動作しないため、object タグで参照する。

import_svg.html
<!DOCTYPE html>
<html>
  <header>
    <title>SVG Test</title>
  </header>
  <body>
    <img src="with_js.svg">
    <object type="image/svg+xml" data="with_js.svg"></object>
  </body>
</html>
30
25
1

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
30
25