Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.

Example:

<object id="img" data="image.svg" width="500" height="300"/> <script>document.getElementById("img").addData([1,23,4]);</script> 

Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document?

like image 346
Staale Avatar asked Sep 26 '08 08:09

Staale


People also ask

Can SVG integrate with JavaScript?

Since SVG images can be inlined in HTML, we can manipulate them with JavaScript. This means that we can animate parts of an image from code, make it interactive, or turn things around and generate graphics from data.

Can you embed SVG in HTML?

You can embed SVG elements directly into your HTML pages.

What is SVG in HTML?

SVG stands for Scalable Vector Graphics. SVG is used to define graphics for the Web. SVG is a W3C recommendation.

What is an embedded SVG?

Embedded content is content that imports into the document from another resource. SVG <image> and <foreignObject> elements are used for SVG embedded content support.


1 Answers

Solution:

in svg:

<script>document.method = function() {}</script> 

in html (using prototype to add event listeners):

<script>$("img").observe("load", function() {$("img").contentDocument.method()}); 

You need to listen to the load event on the image. Once the image is loaded, you can use the element.contentDocument to access the document variable on the svg document. Any methods added to that, will be available.

like image 127
Staale Avatar answered Sep 29 '22 17:09

Staale