html - Javascript: making two circles follow cursor independently, without redundency -
i'm trying yellow
, red
circles in js fiddle below follow cursor independently, how can generalize code if add more circle divs don't have copy redundant code?
http://jsfiddle.net/fhmkf/218/
the code has lot of redudency:
// first circle variables var center = { x: $(".container").width()/2 - 15, y: $(".container").height()/2 - 15 }; var distancethreshold = $(".container").width()/2 - 15; var mousex = 0, mousey = 0; // second circle variables var center2 = { x2: $(".container2").width()/2 - 25, y2: $(".container2").height()/2 - 25 }; var distancethreshold2 = $(".container2").width()/2 - 25; var mousex2 = 0, mousey2 = 0; $(window).mousemove(function(e){ var d = { x: e.pagex - center.x, y: e.pagey - center.y }; var distance = math.sqrt(d.x*d.x + d.y*d.y); if (distance < distancethreshold) { mousex = e.pagex; mousey = e.pagey; } else { mousex = d.x / distance * distancethreshold + center.x; mousey = d.y / distance * distancethreshold + center.y; } var d2 = { x2: e.pagex - 200 - center2.x2, y2: e.pagey - 200 - center2.y2 }; var distance2 = math.sqrt(d2.x2*d2.x2 + d2.y2*d2.y2); if (distance2 < distancethreshold2) { mousex2 = e.pagex - 200; mousey2 = e.pagey - 200; } else { mousex2 = d2.x2 / distance2 * distancethreshold2 + center2.x2; mousey2 = d2.y2 / distance2 * distancethreshold2 + center2.y2; } }); // cache selector var follower = $("#follower"); var xp = 0, yp = 0; var loop = setinterval(function(){ // change 12 alter damping higher slower xp += (mousex - xp) / 2; yp += (mousey - yp) / 2; follower.css({left:xp, top:yp}); }, 30); // cache selector var follower2 = $("#follower2"); var xp2 = 0, yp2 = 0; var loop2 = setinterval(function(){ // change 12 alter damping higher slower xp2 += (mousex2 - xp2) / 2; yp2 += (mousey2 - yp2) / 2; follower2.css({left:xp2, top:yp2}); }, 30);
just create class circles:
(jsfiddle)
var circle = function(container, follower, r){ var center = { x: $(container).width()/2 - r, y: $(container).height()/2 - r }; var distancethreshold = $(container).width()/2 - r; var mousex = 0, mousey = 0; $(window).mousemove(function(e){ var d = { x: e.pagex - center.x, y: e.pagey - center.y }; var distance = math.sqrt(d.x*d.x + d.y*d.y); if (distance < distancethreshold) { mousex = e.pagex; mousey = e.pagey; } else { mousex = d.x / distance * distancethreshold + center.x; mousey = d.y / distance * distancethreshold + center.y; } }); // cache selector var follower = $(follower); var xp = 0, yp = 0; var loop = setinterval(function(){ // change 12 alter damping higher slower xp += (mousex - xp) / 2; yp += (mousey - yp) / 2; follower.css({left:xp, top:yp}); }, 30); }; var c1 = new circle(".container", "#follower", 15); var c2 = new circle(".container2", "#follower2", 25);
if want control circles after circle
object has been initialized, add public "methods" class: this.methodname = function(){ }
Comments
Post a Comment