I would like to create an SVG file that, on it's own, has a little animation, controlled by Javascript. Let's assume that I must use Javascript, not the fancy-pants SVG animation tools. That works just fine; a black circle moves around the top left corner of my window:
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="400px" height="400px"
>
<circle id="c" cx="50px" cy="50px" r="20px" />
<script>
var c = document.getElementById('c');
function f() {
c.setAttribute('cx', 50 + 30 * Math.random());
c.setAttribute('cy', 50 + 30 * Math.random());
}
setInterval(f, 1000);
</script>
</svg>
Now, I would like add that SVG to a few web pages. Let's try:
<html>
<head>
<title>Test a scripted SVG in an <img> tag
</head>
<body>
<img src="test.svg" />
</body>
</html>
The result is a black circle that does not move around.
What am I doing wrong? or Where does it say that I cannot do this?
<script>
elements do work in SVG files but not when the SVG file is displayed as an image whether that is via the <img>
element or as a CSS background-image. If you want scripts to work then replace the <img>
with an <iframe>
or <object>
element.
Basically, SVG when used in an image context emulates raster images. Raster images aren't scriptable so neither is SVG when it is used in that way.
I've done this and it worked for me.
But I think there should be the mysterious //<!\[CDATA\[
stuff:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC
"-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="200"
height="200"
zoomAndPan="disable"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:space="preserve">
<!-- Script linked from the outside-->
<script xlink:href="linked_script.js" />
<script>
//<![CDATA[
alert("ble");
]]>
</script>
</svg>
This is the file I embed it in (and it alert
s as expected):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title>Svg embeding test</title>
</head>
<body>
<embed src="test.svg" type="image/svg+xml" />
</body>
</html>
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