Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Make a Wave using Javascript

Here is what I currently have http://jsfiddle.net/6GEfr/

This works but I want it to be like a wave. Rather than a 'v' shape, it should look like an actual wave. How do you gradually do this?

var height = 0;

setInterval(function () {
    $('#container').prepend('<div style="height:' + Math.abs(height++) + '%"></div>');
    height = (height == 100) ? -100 : height;
}, 10);

my css:

html, body, #outerContainer, #container {
    height:100%;
}
#outerContainer {
    display : table;
}
#container {
    display : table-cell;
    vertical-align:bottom;
    white-space:nowrap;
}
#container > div {
    width:5px;
    background:black;
    display:inline-block;
}
like image 862
user3594098 Avatar asked Dec 19 '22 15:12

user3594098


1 Answers

Just use Math.sin() to model the wave.

Updated Example

var i = 5, height = 0;
setInterval(function () {
    $('#container').prepend('<div style="height:' + height + '%"></div>');
    i += 0.05;
    height = 50 * Math.sin(i) + 50;
}, 10);

If you want to make the wave smoother, decrease the increment value and the width of the elements. Here is an example.

like image 87
Josh Crozier Avatar answered Dec 24 '22 01:12

Josh Crozier