Document Structure – SVG 1.1 (Second Edition) 5.7 The ‘image’ element による SVG のサンプルはこんな感じ。


<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="4in" height="3in" version="1.1"
     xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <desc>This graphic links to an external image
  </desc>
  <image x="200" y="200" width="100px" height="100px"
         xlink:href="myimage.png">
    <title>My image</title>
  </image>
</svg>

JavaScript で SVG 用に 要素を動的に作るには、 名前空間の速修講座 | Mozilla Developer Network によると、こんな感じ。


var SVG_NS = 'http://www.w3.org/2000/svg';
var XLink_NS = 'http://www.w3.org/1999/xlink';
var image = document.createElementNS(SVG_NS, 'image');
image.setAttributeNS(null, 'width', '100');
image.setAttributeNS(null, 'height', '100');
image.setAttributeNS(XLink_NS, 'xlink:href', 'flower.png');

名前空間を認識しているメソッドを使うのが大事。 createElement ではなく createElementNS を、 setAttribute ではなく setAttributeNS を使う。

ちなみに、x,y属性で値を指定する場合は、指定された座標に画像の左上隅がくる。左上がxy座標の(0,0)で、右下方向が正の座標値。

Ref.

tags: svg javascript

Posted by NI-Lab. (@nilab)