Jac*_*ble 3 html javascript animation svg
我想创建一个SVG文件,它本身就有一个小动画,由Javascript控制.让我们假设我必须使用Javascript,而不是花式SVG动画工具.这很好用; 一个黑色圆圈围绕我的窗口左上角移动:
<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>
Run Code Online (Sandbox Code Playgroud)
现在,我想将SVG添加到几个网页中.我们试试吧:
<html>
<head>
<title>Test a scripted SVG in an <img> tag
</head>
<body>
<img src="test.svg" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
结果是一个不会移动的黑色圆圈.
我究竟做错了什么?或者说我不能这样做?
<script>元素在SVG文件中有效,但在SVG文件显示为图像时无论是通过<img>元素还是作为CSS背景图像.如果你想脚本工作,然后更换<img>用<iframe>或<object>元素.
基本上,SVG在图像上下文中使用时模拟光栅图像.光栅图像不可编写脚本,因此当以这种方式使用时,SVG也不是.