云:
<g id="clouds" >
<ellipse x="0" y="0" cx="100" cy="100" rx="30" ry="20" fill="white"/>
<ellipse x="0" y="0" cx="120" cy="80" rx="30" ry="20" fill="white"/>
<ellipse x="0" y="0" cx="130" cy="110" rx="30" ry="20" fill="white"/>
<ellipse x="0" y="0" cx="160" cy="100" rx="30" ry="20" fill="white"/>
<animateTransform attributeName="transform"
attributeType="XML"
type="translate"
from="0,0"
to="6000,0"
dur="30s"
repeatCount="indefinite"/>
</g>
以下是javascript:
var svg = document.getElementsByTagName('svg')[0];
var xlinkns = "http://www.w3.org/1999/xlink";
function loadClouds(){
setInterval(function(){
var y = (Math.random()*1000)+200;
var use = document.createElementNS("http://www.w3.org/2000/svg", 'use');
use.setAttributeNS(xlinkns, "href", "#clouds");
use.setAttribute("transform", "scale(0.2,0.2)");
use.setAttribute("x", 0);
use.setAttribute("y", y);
svg.appendChild(use);
}, 1000);
}
我如何称呼它:
//Clouds
<script type="text/javascript"><![CDATA[
loadClouds();
]]></script>
每次创建云时,都会使用之前创建的云的x作为起点,而不是从0开始。
答案 0 :(得分:1)
“使用”有时可能有点棘手,但你需要的可能是
anim.beginElement();
。这是一个有效的例子:
var svg = document.getElementsByTagName('svg')[0];
var xlinkns = "http://www.w3.org/1999/xlink";
function loadClouds(){
var t0 = Date.now()
setInterval(function(){
var t = Date.now()-t0;
var y = Math.floor((Math.random()*1000))-100;
var use = document.createElementNS("http://www.w3.org/2000/svg", 'use');
use.setAttributeNS(xlinkns, "href", "#clouds");
//use.setAttribute("transform", "");
use.setAttribute("transform", "scale(0.2,0.2)");
use.setAttribute("x",0);
//use.setAttribute("x", t*-0.2);
use.setAttribute("y", y);
//use.transform.animVal[0].matrix.a = Math.random()
var anim = svg.ownerDocument.createElementNS("http://www.w3.org/2000/svg", 'animateTransform');
anim.setAttributeNS(null,'attributeName','transform')
anim.setAttributeNS(null,'attributeType','XML')
anim.setAttributeNS(null,'type','translate')
anim.setAttributeNS(null,'from',"0 0")
anim.setAttributeNS(null,'to',"6000 0")
anim.setAttributeNS(null,'dur',"30s")
anim.setAttributeNS(null,'additive','sum')
anim.setAttributeNS(null,'repeatCount',"indefinite")
use.appendChild(anim);
svg.appendChild(use);
anim.beginElement();
}, 1000);
}
loadClouds();
body {
background: blue
}
<svg>
<g id="clouds">
<ellipse x="0" y="0" cx="100" cy="100" rx="30" ry="20" fill="white"/>
<ellipse x="0" y="0" cx="120" cy="80" rx="30" ry="20" fill="white"/>
<ellipse x="0" y="0" cx="130" cy="110" rx="30" ry="20" fill="white"/>
<ellipse x="0" y="0" cx="160" cy="100" rx="30" ry="20" fill="white"/>
</g>
</svg>
当然,还有很多工作要做,但它应该会帮助你前进。