teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

教えていただいた内容を反映

2020/09/28 14:10

投稿

match12
match12

スコア21

title CHANGED
File without changes
body CHANGED
@@ -39,12 +39,16 @@
39
39
  $('[name="addBtn"]').on('click', function(){
40
40
  let svg_doc = document.getElementById('test_obj').contentDocument;
41
41
  let src = 'test2.png';
42
+
42
- var obj = '<image xmlns="http://www.w3.org/2000/svg" id="test" data-name="" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="'+src+'"/>';
43
+ var image = document.createElementNS("http://www.w3.org/2000/svg", "image");
44
+ image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', src);
45
+ image.setAttributeNS(null, 'id', 'test');
43
- $(svg_doc).find('#base').append(obj);
46
+ image.setAttributeNS(null, 'width', 64);
47
+ image.setAttributeNS(null, 'height', 64);
48
+ svg_doc.appendChild(image);
44
49
 
45
- $(obj).ready(function() {
50
+ $(image).ready(function() {
46
- let test1 = $(svg_doc).find('#test');
47
- $(test1).draggable();
51
+ $(image).draggable();
48
52
  });
49
53
  });
50
54
 

1

文章が途中で切れてしまっていたので修正

2020/09/28 14:10

投稿

match12
match12

スコア21

title CHANGED
File without changes
body CHANGED
@@ -1,6 +1,7 @@
1
1
  現在、SVGの勉強をしており、その中でsvgファイルへ動的に画像を追加し、
2
2
  その画像をドラッグ&ドロップで動かせる様にしたいと考えています。
3
3
 
4
+ 現在のソースとしては以下の通りです。
4
5
  - html
5
6
  ```html
6
7
 
@@ -22,7 +23,7 @@
22
23
  <body>
23
24
 
24
25
  <object id="test" type="image/svg+xml" data="test.svg"></object>
25
- <button name="addBtn">追加<
26
+ <button name="addBtn">追加</button>
26
27
  </body>
27
28
  </html>
28
29
 
@@ -31,4 +32,33 @@
31
32
  ```svg
32
33
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1128.04 1272.27"><g class="cls-2"><g id="base"><image width="800" height="600" xlink:href="test.png"/></g></g></svg>
33
34
  ```
34
- - js
35
+ - js
36
+ ```javascript
37
+ $(function() {
38
+
39
+ $('[name="addBtn"]').on('click', function(){
40
+ let svg_doc = document.getElementById('test_obj').contentDocument;
41
+ let src = 'test2.png';
42
+ var obj = '<image xmlns="http://www.w3.org/2000/svg" id="test" data-name="" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="'+src+'"/>';
43
+ $(svg_doc).find('#base').append(obj);
44
+
45
+ $(obj).ready(function() {
46
+ let test1 = $(svg_doc).find('#test');
47
+ $(test1).draggable();
48
+ });
49
+ });
50
+
51
+ });
52
+ ```
53
+
54
+ 問題点
55
+ > document.getElementById('test_obj').contentDocument;
56
+
57
+ これがnullとなってしまいます。
58
+ document.getElementById('test_obj')自体でobject自体は取れているのですが
59
+ 中身が取れていないので読み込みタイミングなどが原因なのかなとは思うのですが
60
+ どの様に対応すればいいのかがわかりません。
61
+
62
+ svg、javascriptへの知識が浅いため大変稚拙な説明となってしまっているかもしれませんが
63
+ ご有識者の方、お知恵を貸していただけたらと思います。
64
+ よろしくお願い致します。