what i am trying to do here, is that, I add a small image and it will be moving around the body.. But the problem is, i wanted the small image to be moving ard in the svg box.. I tried to take the SVG ID and let it append the image.. It will still move out of the svg box.. I wonder, if i missed out some codings?
$(window).load(function(){
$(document).ready(function(e) {
var num = 0;
var interval;
/*var svg = d3.select("main").append("svg:svg")
.attr("width", w)
.attr("height", h);
*/
$('#add').click(function(e) {
$('#box').append('<div class="predator" id="predator'+ num + '"><img src="Pictures/PondSpecies/anchovies.png"></div>');
$('#predator'+num).css({
left: randomRange(500,150),
top: randomRange(400,150)
});
if (interval)
clearInterval(interval);
interval = setInterval (function () {
for (var i=0; i<num; i++) {
$('#predator'+i).animate ({
left: '+=' + randomRange(-11,11),
top: '+=' + randomRange(-11,11)
s /* Extra */
//if (x < 0 || x > w) SVG.vx *= -1;
//if (y < 0 || y > h) SVG.vy *= -1;
}, 100);
}
}, 100);
num++;
});
$('#remove').click(function(e) {
num--;
$('#predator' + num).remove();
if (num == 0 && interval)
clearInterval(interval);
});
});
/* FUNCTIONS */
function randomRange(min, max) {
return Math.random() * (max-min) + min;
}
});
HTML body:
<div id="box">
<SVG xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" id="main" style="border:solid 1px #000000;width:515;height:474;">
<image xlink:href="Pictures/PondEnvironment/pond.png" x="0" y="0" width="513" height="474" />
</SVG>
</div>
Many thanks in advance for helping!
If you want to keep your predators inside the SVG when animating, you’ll need to check their new positions each time. This fiddle should help:
http://jsfiddle.net/DJg36/18/
Also, I don’t think your animations were finishing completely, meaning they were starting to queue, possibly causing some confusions, so just to be sure, you should call stop() before animating again.
So something like this is needed:
Hope this helps!
Andy