code_junkie

Is it possible to manipulate an SVG document embedded in an HTML doc with JavaScript?

Nov 11th, 2011
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. <object id="img" data="image.svg" width="500" height="300"/>
  2. <script>document.getElementById("img").addData([1,23,4]);</script>
  3.  
  4. <script>document.method = function() {}</script>
  5.  
  6. <script>$("img").observe("load", function() {$("img").contentDocument.method()});
  7.  
  8. /****************** Track and handle SVG object movement *************/
  9. var svgDoc;
  10. var svgRoot;
  11. var mover=''; //keeps track of what I'm dragging
  12.  
  13. ///start function////
  14. //do this onload
  15. function start(evt){
  16. //set up the svg document elements
  17. svgDoc=evt.target.ownerDocument;
  18. svgRoot=svgDoc.documentElement;
  19. //add the mousemove event to the whole thing
  20. svgRoot.addEventListener('mousemove',go,false);
  21. //do this when the mouse is released
  22. svgRoot.addEventListener('mouseup',releaseMouse,false);
  23. }
  24.  
  25. // set the id of the target to drag
  26. function setMove(id){ mover=id; }
  27.  
  28. // clear the id of the dragging object
  29. function releaseMouse(){
  30. if(allowMoves == true){ sendMove(mover); }
  31. mover='';
  32. }
  33.  
  34. // this is launched every mousemove on the doc
  35. // if we are dragging something, move it
  36. function go(evt){
  37. if(mover != '' && allowMoves != false) {
  38. //init it
  39. var me=document.getElementById(mover);
  40.  
  41. //actually change the location
  42. moveX = evt.clientX-135; //css positioning minus 1/2 the width of the piece
  43. moveY = evt.clientY-65;
  44. me.setAttributeNS(null, 'x', evt.clientX-135);
  45. me.setAttributeNS(null, 'y', evt.clientY-65);
  46. }
  47. }
  48.  
  49. function moveThis(pieceID, x, y) {
  50. $(pieceID).setAttributeNS(null, 'x', x);
  51. $(pieceID).setAttributeNS(null, 'y', y);
  52. }
  53.  
  54. <script type="text/javascript">
  55. function change(){
  56. var s=document.getElementById("cube");
  57. s.setAttribute("stroke","0000FF");
  58. }
  59. </script>
  60.  
  61. <svg width=100 height=100 style='float: left;'>
  62. <rect x="10" y="10" width="60" height="60" id="cube" onclick="change()" stroke=#F53F0C stroke-width=10 fill=#F5C60C />
  63. </svg>
  64.  
  65. <button onclick="change()">Click</button>
Add Comment
Please, Sign In to add comment