zelusp zelusp - 3 months ago 9
CSS Question

How to asynchronously move multiple overlayed images using javascript?

I have 10 shapes that collectively define a square image as shown below. I would like to move each image using the output of a periodic function like sine that takes user mouse position as an input. Each image should have a different frequency and period affecting it's motion so that as a user mouses over the scene the shapes jitter past each other.

enter image description here

So far I've managed to get 1 shape to move using this:

$(document).mousemove(function(e){
var track = function(ampl, freq) {
return {
x : ampl * Math.sin(freq*e.pageX),
y : ampl*1.6 * Math.sin(freq*e.pageY)
};
}

var current = track(10, 0.05);
$("#image").css({left:current.x, top:current.y});

});


How can I get this jsfiddle to do that for the other 9 shapes?

Answer

I would do something like this - http://jsfiddle.net/jfhk8bye/

track = function(ampl, freq, pageX, pageY) {
    return {
        x   : ampl * Math.sin(freq*pageX),
        y   : ampl*1.6 * Math.sin(freq*pageY)
    };
}
$imgs = $('img.image')
$(document).mousemove(function(e)
{
    $imgs.each(function()
  {
    var $img = $(this);
    var current = track($img.data('ampl'), $img.data('freq'), e.pageX, e.pageY);
    console.log(current);
    $img.css({left:current.x, top:current.y});
  });
});

What I did:

  • Qualified image IDs into classes instead (updating CSS too)
  • Added data attributes to the image elements representing their frequencies and amplitudes (this way you can control these values in HTML)
  • Updated your javascript appropriately and optimised it.