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?
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.
You can embed SVG elements directly into your HTML pages.
SVG stands for Scalable Vector Graphics. SVG is used to define graphics for the Web. SVG is a W3C recommendation.
Embedded content is content that imports into the document from another resource. SVG <image> and <foreignObject> elements are used for SVG embedded content support.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With