September 4, 2007
JSVGCanvas
JSVGCanvas
// A canvas to show "squiggle.svg"
JSVGCanvas c = new JSVGCanvas();
String uri = new File("squiggle.svg").toURI().toString();
c.setURI(uri);
// A frame for the canvas to live in
JFrame f = new JFrame(uri);
f.setSize(600, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the canvas to the frame
f.getContentPane().add(c);
// Show the frame
f.setVisible(true);
JSVGCanvas
constructorsJSVGCanvas(SVGUserAgent ua,
boolean eventsEnabled,
boolean selectableText)
ua — Object that provides the canvas with access to the “outside world”
eventsEnabled — Whether UI interactions will dispatch DOM events
selectableText — Whether text in SVG documents can be highlighted with the mouse
JSVGCanvas()
JSVGCanvas(null, true, true)
.SVGUserAgent
interfaceString getDefaultFontFamily()
String getLanguages()
String getPixelUnitToMillimeter()
String getUserStyleSheetURI()
void openLink(String uri, boolean newc)
void showAlert(String message)
alert()
.alert()
ed messages to go to a JTextArea
.<text x='300' y='50' font-size='36' text-anchor='middle'>Click a circle:</text>
<g stroke='#444' stroke-width='5'>
<circle cx='100' cy='130' r='40' fill='#f66' onclick='alert("You clicked red.")'/>
<circle cx='300' cy='130' r='40' fill='#6f6' onclick='alert("You clicked green.")'/>
<circle cx='500' cy='130' r='40' fill='#66f' onclick='alert("You clicked blue.")'/>
</g>
// A text area for messages
final JTextArea t = new JTextArea();
t.setPreferredSize(new Dimension(600, 100));
…
// A user agent object
SVGUserAgent ua = new SVGUserAgentAdapter() {
public void showAlert(String message) {
t.append(message + "\n");
}
};
// A canvas to show "circles.svg"
JSVGCanvas c = new JSVGCanvas(ua, true, false);
String uri = new File("circles.svg").toURI().toString();
c.setURI(uri);
// A frame for the canvas to live in
JFrame f = new JFrame(uri);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(c);
f.getContentPane().add(t, BorderLayout.SOUTH);
…
org.apache.batik.swing.gvt.Interactor
interface Interactor extends KeyListener, MouseListener,
MouseMotionListener {
boolean startInteraction(InputEvent ie);
boolean endInteraction();
}
public class CenteringInteractor extends InteractorAdapter {
protected boolean isDoubleClick(InputEvent ie) {
if (ie instanceof MouseEvent) {
MouseEvent me = (MouseEvent) ie;
return me.getID() == MouseEvent.MOUSE_CLICKED
&& me.getButton() == MouseEvent.BUTTON1
&& me.getClickCount() == 2;
}
return false;
}
public boolean startInteraction(InputEvent ie) {
return isDoubleClick(ie);
}
public boolean endInteraction() {
return true;
}
...
public void mouseClicked(MouseEvent me) {
if (isDoubleClick(me)) {
JSVGCanvas c = (JSVGCanvas) me.getSource();
int cx = c.getWidth() / 2;
int cy = c.getHeight() / 2;
int x = me.getX();
int y = me.getY();
AffineTransform at =
AffineTransform.getTranslateInstance(cx - x, cy - y);
AffineTransform rt =
(AffineTransform) c.getRenderingTransform().clone();
rt.preConcatenate(at);
c.setRenderingTransform(rt);
}
}
}
JSVGCanvas c = ...;
c.getInteractors().add(new CenteringInteractor());
org.apache.batik.swing.gvt.Overlay
interface Overlay {
void paint(Graphics g);
}
public class CentreSymbolOverlay implements Overlay {
protected JSVGCanvas canvas;
public CentreSymbolOverlay(JSVGCanvas canvas) {
this.canvas = canvas;
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int w = canvas.getWidth();
int h = canvas.getHeight();
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2f));
g2d.drawRect(w / 2 - 10, h / 2 - 10, 20, 20);
g2d.drawLine(w / 2, h / 2 - 13, w / 2, h / 2 - 7);
g2d.drawLine(w / 2, h / 2 + 7, w / 2, h / 2 + 13);
g2d.drawLine(w / 2 - 13, h / 2, w / 2 - 7, h / 2);
g2d.drawLine(w / 2 + 7, h / 2, w / 2 + 13, h / 2);
}
}
JSVGCanvas c = ...;
c.getOverlays().add(new CentreSymbolOverlay(c));
org.w3c.dom.DOMImplementation
somehowcreateDocument()
on the DOMImplementation
object
to create a new object that implements org.w3c.dom.Document
Document
object and other newly created nodes to build the documentDOMImplementation
object is obtained using
org.apache.batik.dom.svg.SVGDOMImplementation
.getDOMImplementation()
<svg xmlns='http://www.w3.org/2000/svg'
width='400' height='450'>
<rect x='10' y='20' width='100' height='50' fill='red'/>
</svg>
// Get a DOMImplementation object
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// Create a new document
String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
Document doc = impl.createDocument(svgNS, "svg", null);
// Get the root element (the 'svg' element).
Element svgRoot = doc.getDocumentElement();
// Set the width and height attributes on the root 'svg' element.
svgRoot.setAttributeNS(null, "width", "400");
svgRoot.setAttributeNS(null, "height", "450");
// Create the rectangle.
Element rectangle = doc.createElementNS(svgNS, "rect");
rectangle.setAttributeNS(null, "x", "10");
rectangle.setAttributeNS(null, "y", "20");
rectangle.setAttributeNS(null, "width", "100");
rectangle.setAttributeNS(null, "height", "50");
rectangle.setAttributeNS(null, "fill", "red");
// Attach the rectangle to the root 'svg' element.
svgRoot.appendChild(rectangle);
SAXSVGDocumentFactory
class does the parsingInputStream
or Reader
createDocument(String uri)
createDocument(String uri, InputStream inp)
createDocument(String uri, Reader r)
Document
objects are also org.w3c.dom.svg.SVGDocument
s
String theXML = "<svg xmlns='http://www.w3.org/2000/svg' width='400' ...";
try {
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
// Construct a document from XML in a string
StringReader r = new StringReader(theXML);
Document doc1 = f.createDocument(r);
// Construct a document from XML at a URI
String uri = "http://xmlgraphics.apache.org/batik/demo/barChart.svg";
Document doc2 = f.createDocument(uri);
} catch (IOException ioe) {
// ...
}
We can:
JSVGCanvas
Document
in a JSVGCanvas
JSVGCanvas.setSVGDocument()
to show
an SVGDocument
in a canvasRendering process steps:
setSVGDocument()
was used)A listener for each step:
SVGDocumentLoaderListener
,
GVTTreeBuilderListener
,
SVGLoadEventDispatcherListener
,
GVTTreeRendererListener
,
UpdateManagerListener
JSVGCanvas
defaults to auto-detecting based on contentJSVGCanvas.setDocumentState(JSVGCanvas.ALWAYS_STATIC)
or JSVGCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC)
JSVGCanvas
SVGDocument
and cause the
canvas to be updatedJSVGCanvas
JSVGCanvas
The document to modify:
<svg xmlns='http://www.w3.org/2000/svg'
width='400' height='300'
font-size='32' font-family='"Bitstream Vera Sans"' text-anchor='middle'
text-rendering='geometricPrecision' shape-rendering='geometricPrecision'>
<g transform='translate(200,150)'>
<g id='rotationGroup'>
<rect x='-120' y='-24' width='240' height='48' rx='8'
stroke='#478' stroke-width='3' fill='#cef'/>
<text y='12'>Rotating text</text>
</g>
</g>
</svg>
JSVGCanvas
Listen for a SVGLoadEventDispatcherEvent
to begin the rotations:
// A canvas to show "text.svg"
JSVGCanvas c = new JSVGCanvas();
c.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// Timer task that will do the rotation
final RotationTimerTask tt = new RotationTimerTask(c);
// Start the timer when the document is ready
c.addSVGLoadEventDispatcherListener(new SVGLoadEventDispatcherAdapter() {
public void svgLoadEventDispatchCompleted(SVGLoadEventDispatcherEvent e) {
new Timer().scheduleAtFixedRate(tt, 500, 500);
}
});
// Load the document
c.setURI(new File("text.svg").toURI().toString());
JSVGCanvas
class RotationTimerTask extends TimerTask {
JSVGCanvas canvas;
int angle;
public RotationTimerTask(JSVGCanvas canvas) { this.canvas = canvas; }
public void run() {
// Increment the angle
angle += 10;
// Find the <g> element to rotate
Document doc = canvas.getSVGDocument();
final Element g = doc.getElementById("rotationGroup");
// Schedule the rotation in the update manager's thread
Runnable rotationUpdater = new Runnable() {
public void run() {
g.setAttributeNS(null, "transform", "rotate(" + angle + ")");
}
};
canvas.getUpdateManager().getUpdateRunnableQueue().invokeLater
(rotationUpdater);
}
}
JSVGCanvas
SVGDocument
BridgeContext
In general:
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.gvt.GraphicsNode;
SVGDocument doc = ...;
UserAgent userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
GVTBuilder builder = new GVTBuilder();
GraphicsNode rootGN = builder.build(ctx, doc);
We want to get the bounding box of an arbitrary text string:
<svg xmlns='http://www.w3.org/2000/svg'>
<text x='100' y='100'>The text here</text>
</svg>
String SVGNS = "http://www.w3.org/2000/svg";
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
Document doc = impl.createDocument(SVGNS, "svg", null);
Element text = doc.createElementNS(SVGNS, "text");
text.setAttributeNS(null, "x", "100");
text.setAttributeNS(null, "y", "100");
text.appendChild(doc.createTextNode("The text here"));
doc.getDocumentElement().appendChild(text);
UserAgent ua = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(ua);
BridgeContext ctx = new BridgeContext(ua, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
GVTBuilder builder = new GVTBuilder();
GraphicsNode rootGN = builder.build(ctx, doc);
SVGRect bbox = ((SVGLocatable) text).getBBox();
System.out.println
("(" + bbox.getX() + "," + bbox.getY() + ","
+ bbox.getWidth() + "," + bbox.getHeight() + ")");
The org.apache.batik.svggen.XmlWriter
class can serialise a Node
public static void writeXml(Node node,
Writer writer,
boolean escaped)
node — The DOM node to serialise
writer — Where to write the serialisation to
escaped — Whether non-ASCII characters should be written as numeric character references
importClass()
or importPackage()
to bring the class into scopenew
to create instances of the Java classes<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="50" fill="green" onclick="showFrame()"/>
<script>
importPackage(Packages.javax.swing);
function showFrame() {
var frame = new JFrame("My test frame");
var label = new JLabel("Hello from Java objects created in ECMAScript!");
label.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(label);
frame.setSize(400, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
</script>
</svg>
Interpreter
objectJSVGCanvas
has a BridgeContext
,
which has the interpreters for a documentJSVGCanvas
to get access to it<svg xmlns='http://www.w3.org/2000/svg'
width='400' height='300' viewBox='0 0 400 300'>
<script><![CDATA[
importClass(Packages.java.awt.Frame);
function maximizeFrame() {
var newState;
if (frame.getExtendedState() & Frame.MAXIMIZED_BOTH) {
newState = Frame.NORMAL;
} else {
newState = Frame.MAXIMIZED_BOTH;
}
frame.setExtendedState(newState);
}
]]></script>
<text x='200' y='150' fill='blue' text-decoration='underline'
text-anchor='middle' font-size='32px' font-weight='bold'
cursor='pointer' onclick='maximizeFrame()'>
Click me!
</text>
</svg>
Interpreter
The Interpreter
interface has:
void bindObject(String name, Object object);
Extend JSVGCanvas
to get access to the Interpreter
:
class MyCanvas extends JSVGCanvas {
public void bindObjectInES(String name, Object value) {
Interpreter i = bridgeContext.getInterpreter("text/ecmascript");
i.bindObject(name, value);
}
}
// A frame for the canvas to live in
final JFrame f = new JFrame("Binding example");
f.setSize(400, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// A canvas to show "max.svg"
final MyCanvas c = new MyCanvas();
// When the document is loaded, bind the JFrame to the variable "frame"
c.addSVGLoadEventDispatcherListener(new SVGLoadEventDispatcherAdapter() {
public void svgLoadEventDispatchCompleted(SVGLoadEventDispatcherEvent e) {
c.bindObjectInES("frame", f);
}
});
c.setURI(new File("max.svg").toURI().toString());
// Add the canvas to the frame
f.getContentPane().add(c);
// Show the frame
f.setVisible(true);
The Interpreter
interface also has:
Object evaluate(Reader scriptreader);
Object evaluate(String script);
Again, we must extend JSVGCanvas
to get at it.
class MyCanvas extends JSVGCanvas {
public Object evaluateInES(String script) {
Interpreter i = bridgeContext.getInterpreter("text/ecmascript");
return i.evaluate(script);
}
}
SVGGraphics2D
SVG generatorGraphics2D
that generates SVGSVGGraphics2D
SVG generatorSVGGraphics2D
is a three-step process:
Document
to be used as a factorySVGGraphics2D
SVGGraphics2D
constructorsSVGGraphics2D(Document domFactory)
SVGGraphics2D(Document domFactory, ImageHandler imageHandler,
ExtensionHandler extensionHandler,
boolean textAsShapes)
SVGGraphics2D(SVGGeneratorContext generatorCtx,
boolean textAsShapes)
SVGGeneratorContext
.SVGGraphics2D
// Get a DOMImplementation.
DOMImplementation domImpl =
SVGDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document.
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
// Create an instance of the SVG Generator.
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
// Paint on the SVG Graphics2D implementation.
svgGenerator.setPaint(Color.red);
svgGenerator.fill(new Rectangle(10, 10, 100, 100));
// Finally, stream out SVG to the standard output using UTF-8 encoding.
boolean useCSS = true; // we want to use CSS style attributes
Writer out = new OutputStreamWriter(System.out, "UTF-8");
svgGenerator.stream(out, useCSS);
DOMImplementation impl =
GenericDOMImplementation.getDOMImplementation();
String svgNS = "http://www.w3.org/2000/svg";
Document myFactory = impl.createDocument(svgNS, "svg", null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
ctx.setComment("Generated by FooApplication with Batik SVG Generator");
SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);
SVGGraphics2D
to embed fonts<font>
elements will be created// Get a DOMImplementation.
DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document.
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
// Create an instance of the SVG Generator with a context that has font embedding turned on.
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
ctx.setEmbeddedFontsOn(true);
SVGGraphics2D svgGenerator = new SVGGraphics2D(ctx, false);
// Paint on the SVG Graphics2D implementation.
Font f = new Font("Trebuchet MS", Font.PLAIN, 36);
svgGenerator.setPaint(Color.blue);
svgGenerator.setFont(f);
svgGenerator.drawString("Some text!", 50, 50);
// Finally, stream out SVG to the standard output using UTF-8 encoding.
svgGenerator.stream(new OutputStreamWriter(System.out, "UTF-8"), false);
SVGGraphics2D
usesjava -jar batik-ttf2svg.jar <ttf-path>
[-l <range-begin>] [-h <range-end>]
[-autorange]
[-id <id>]
[-o <output-path>]
[-testcard]
SVGGraphics2D
uses data:
URIsImageHandler
ImageHandler
// Create a factory document.
DOMImplementation impl =
GenericDOMImplementation.getDOMImplementation();
String svgNS = "http://www.w3.org/2000/svg";
Document myFactory = impl.createDocument(svgNS, "svg", null);
// Create the SVGGraphics2D with a custom ImageHandler.
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
ImageHandlerPNGEncoder ihandler =
new ImageHandlerPNGEncoder("res/images", null);
ctx.setImageHandler(ihandler);
SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);
// Paint on g2d.
...
ImageHandler
// Create a factory document.
DOMImplementation impl =
GenericDOMImplementation.getDOMImplementation();
String svgNS = "http://www.w3.org/2000/svg";
Document myFactory = impl.createDocument(svgNS, "svg", null);
// Create the SVGGraphics2D with a custom ImageHandler.
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
// Reuse our embedded base64-encoded image data.
CachedImageHandlerBase64Encoder ihandler =
new CachedImageHandlerBase64Encoder();
ctx.setGenericImageHandler(ihandler);
SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);
// Paint on g2d.
...
Transcoder
TranscoderInput
TranscoderOutput
TranscodingHints
ErrorHandler
// Create a JPEG transcoder.
JPEGTranscoder t = new JPEGTranscoder();
// Set the transcoding hints.
t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(.8));
// Create the transcoder input.
String svgURI = new File(args[0]).toURL().toString();
TranscoderInput input = new TranscoderInput(svgURI);
// Create the transcoder output.
OutputStream ostream = new FileOutputStream("out.jpg");
TranscoderOutput output = new TranscoderOutput(ostream);
// Save the image.
t.transcode(input, output);
// Flush and close the stream.
ostream.flush();
ostream.close();
Use Transcoder.addTranscodingHint(TranscodingHints.Key, Object)
.
Key | Value type |
---|---|
ImageTranscoder.KEY_BACKGROUND_COLOR | Paint |
SVGAbstractTranscoder.KEY_WIDTH | Float |
SVGAbstractTranscoder.KEY_HEIGHT | Float |
SVGAbstractTranscoder.KEY_MAX_HEIGHT | Float |
SVGAbstractTranscoder.KEY_MAX_WIDTH | Float |
SVGAbstractTranscoder.KEY_AOI | Rectangle2D |
SVGAbstractTranscoder.KEY_MEDIA | String |
SVGAbstractTranscoder.KEY_ALTERNATE_STYLESHEET | String |
SVGAbstractTranscoder.KEY_USER_STYLESHEET_URI | String |
SVGAbstractTranscoder.KEY_PIXEL_TO_MM | Float |
SVGAbstractTranscoder.KEY_LANGUAGE | String |
SVGAbstractTranscoder.KEY_EXECUTE_ONLOAD | Boolean |
SVGAbstractTranscoder.KEY_SNAPSHOT_TIME | Boolean |
PDFTranscoder
generates PDF documentsKey | Value type |
---|---|
PDFTranscoder.KEY_STROKE_TEXT | Boolean |
PDFTranscoder.KEY_DEVICE_RESOLUTION | Float |
java -jar batik-rasterizer.jar
[-d <output-dir-or-file>]
[-m <output-mime-type>]
[-w <width>] [-h <height>]
[-a <x>,<y>,<w>,<h>]
...
<input-files>
java -jar batik-rasterizer.jar ...
for every documentjavax.servlet.http.HttpServlet
void doGet(HttpServletRequest req, HttpServletResponse resp)
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Transcoding servlet</display-name>
<description>
A servlet that transcodes an SVG document to PNG
</description>
<servlet>
<servlet-name>TranscodingServlet</servlet-name>
<servlet-class>TranscodingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TranscodingServlet</servlet-name>
<url-pattern>/transcode</url-pattern>
</servlet-mapping>
</web-app>
public class TranscodingServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("image/png");
String uri = request.getParameter("uri");
int width = Integer.parseInt(request.getParameter("width"));
int height = Integer.parseInt(request.getParameter("height"));
PNGTranscoder t = new PNGTranscoder();
t.addTranscodingHint(ImageTranscoder.KEY_WIDTH, new Float(width));
t.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, new Float(height));
TranscoderInput input = new TranscoderInput(uri);
TranscoderOutput output = new TranscoderOutput(response.getOutputStream());
try {
t.transcode(input, output);
} catch (TranscoderException ex) {
throw new ServletException(ex);
}
}
}
<applet>
DOM object— HTML —
<html>
...
<applet id="theApplet" code="...">
</applet>
<script>
var theApplet = document.getElementById("theApplet");
theApplet.f(123);
</script>
</html>
— Java —
public class MyApplet extends JApplet {
...
public void f(int x) {
// ...
}
}
http://xmlgraphics.apache.org/batik/demo.html
<applet archive="batik-anim.jar,batik-awt-util.jar,batik-bridge.jar,
batik-css.jar,batik-dom.jar,batik-ext.jar,
batik-gvt.jar,batik-parser.jar,batik-svg-dom.jar,
batik-script.jar,batik-swing.jar,batik-util.jar,
batik-xml.jar,xml-apis.jar,xml-apis-ext.jar"
code="AppletDemo.class" codebase="demo/" mayscript="mayscript"
width="400" height="300" id="chart">
</applet>
...
<input type="text" value="10" id="ShoeBar">
<input type="text" value="10" id="CarBar">
...
<button onclick="update()">Update chart</button>
function update() {
updateBar("ShoeBar");
updateBar("CarBar");
updateBar("TravelBar");
updateBar("ComputerBar");
}
function updateBar(name) {
var chart = document.getElementById("chart");
var input = document.getElementById(name);
var value = Number(input.value);
if (!isNaN(value) && value >= 0) {
chart.updateBar(name, value);
}
}
public class AppletDemo extends JApplet {
protected JSVGCanvas canvas;
protected Document doc;
protected Element svg;
...
public void updateBar(final String name, final float value) {
canvas.getUpdateManager().getUpdateRunnableQueue().invokeLater
(new Runnable() {
public void run() {
Element bar = doc.getElementById(name);
if (bar == null) {
return;
}
Node n;
Element path1, path2, path3;
... get the three <paths> that make up the bar ...
int offset;
if (name.equals("ShoeBar")) {
offset = 0;
} else if (name.equals("CarBar")) {
offset = 79;
} else if (name.equals("TravelBar")) {
offset = 158;
} else {
offset = 237;
}
String d = "M " + (offset + 86) + ",240 v -" + (3.7 * value) + ...;
path1.setAttributeNS(null, "d", d);
d = "M " + (offset + 86) + "," + (240 - 3.7 * value) + ...;
path2.setAttributeNS(null, "d", d);
d = "M " + (offset + 47) + "," + (240 - 3.7 * value) + " v " + ...;
path3.setAttributeNS(null, "d", d);
}
});
}
}
netscape.javascript.JSObject
represents a script objectJSObject.getWindow(Applet)
returns the global objectJSObject
methodsWe want to use the circles example again, but to update the HTML instead of write to a JTextArea
.
<div id="msg" style="font-size: 32px">Applet HTML example.</div>
<applet archive="lib/batik-anim.jar,lib/batik-awt-util.jar,lib/batik-bridge.jar,
lib/batik-css.jar,lib/batik-dom.jar,lib/batik-ext.jar,
lib/batik-gvt.jar,lib/batik-parser.jar,lib/batik-svg-dom.jar,
lib/batik-script.jar,lib/batik-swing.jar,lib/batik-util.jar,
lib/batik-xml.jar,lib/xml-apis.jar,lib/xml-apis-ext.jar"
code="AppletHTMLExample.class" mayscript="mayscript"
width="600" height="200">
</applet>
<svg xmlns='http://www.w3.org/2000/svg'
xmlns:xlink='http://www.w3.org/1999/xlink'
width='600' height='200' viewBox='0 0 600 200'
shape-rendering='geometricPrecision'
text-rendering='geometricPrecision'>
<text x='300' y='50' font-size='36' text-anchor='middle'>
Click a circle:
</text>
<g stroke='#444' stroke-width='5'>
<circle id='red' cx='100' cy='130' r='40' fill='#f66'/>
<circle id='green' cx='300' cy='130' r='40' fill='#6f6'/>
<circle id='blue' cx='500' cy='130' r='40' fill='#66f'/>
</g>
</svg>
AppletHTMLExample
appletprotected JSVGCanvas canvas;
protected Document doc;
public void init() {
// Create a canvas and load circles2.svg.
canvas = new JSVGCanvas();
getContentPane().add(canvas);
try {
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
URL url = new URL(getCodeBase(), "circles2.svg");
doc = f.createDocument(url.toString());
// Add event listeners to the circles.
((EventTarget) doc.getElementById("red"))
.addEventListener("click", this, false);
((EventTarget) doc.getElementById("green"))
.addEventListener("click", this, false);
((EventTarget) doc.getElementById("blue"))
.addEventListener("click", this, false);
} catch (Exception ex) {
}
}
AppletHTMLExample
appletpublic void start() {
// Display the SVG document.
canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
canvas.setDocument(doc);
}
public void stop() {
// Remove the SVG document.
canvas.setDocument(null);
}
public void handleEvent(Event evt) {
// Update the HTML document when a circle is clicked.
String name = ((Element) evt.getTarget()).getAttributeNS(null, "id");
JSObject win = JSObject.getWindow(this);
JSObject document = (JSObject) win.getMember("document");
JSObject div =
(JSObject) document.call("getElementById", new Object[] { "msg" });
div.setMember("innerHTML", "You clicked the " + name + " circle.");
}