| | | | Browse by category |
Question
How can I use script code in my SVG file?
Answer
The SVG specification describes how to plug script code into an SVG document. This is explained in detail in this section:
SVG Specification - Chapter 18 - Scripting
http://www.w3.org/TR/SVG11/script.html
The key to the scripting capabilities is to add a <script>
section to the <svg>
tag to define the ECMAScript code, with visibility for the whole document. The script functions defined there can be invoked from the onclick
, onload
, and other such attributes set on the elements of the SVG document.
The attached sample performs these actions on an SVG file generated by JViews: the SVGDocumentBuilder
class is responsible for building the DOM structure of the SVG document. In particular, the sample overrides the translate
and afterBuildingDocument
methods to add the scripting capabilities to the final document.
To test the sample, compile the attached class with
javac ScriptInSVGOutput.java
and run it with
java ScriptInSVGOutput
A window shows two rectangles in the JViews manager and an output.svg
file is produced. Open this file in an SVG-capable browser (such as IE with SVG plug-in) and the same two rectangles will be visible in the browser. Clicking the rectangles in the browser causes a message window to be displayed. This window is invoked from the embedded script code.
Note: In order to run this sample in JViews 8.7 or newer, you must call the ilog.views.util.IlvProductUtil.DeploymentLicenceRequired method with the appropriate argument.
section to the tag to define the ECMAScript code, with
visibility for the whole document.
The script functions defined there can be invoked from the onclick
,
onload
, and other such attributes set on the elements of the SVG
document.
The attached sample performs these actions on an SVG file generated by
JViews: the SVGDocumentBuilder
class is responsible for building
the DOM structure of the SVG document. In particular, the sample
overrides the translate
and afterBuildingDocument
methods to add the scripting capabilities to the final document.
To test the sample, compile the attached class with
javac ScriptInSVGOutput.java
and run it with
java ScriptInSVGOutput
A window shows two rectangles in the JViews manager and an
output.svg
file is produced. Open this file
in an SVG-capable browser (such as IE with SVG plug-in) and the same
two rectangles will be visible in the browser. Clicking the rectangles
in the browser causes a message window to be displayed. This window is invoked
from
the embedded script code.
Download Sample
.
**Navigate to technote on IBM web to download image:aid=1****Navigate to technote on IBM web to download the file: ScriptInSVGOutput.java