sine-waves.js
Generate multiple configurable sine waves using a canvas
element

NPM
npm install sine-waves-tns --save
Basic Usage
var waves = new SineWaves({
el: document.getElementById('waves'),
speed: 8,
rotate: 0,
ease: 'Linear',
waveWidth: '95%',
waves: [
{
timeModifier: 1,
lineWidth: 3,
amplitude: 150,
wavelength: 200,
segmentLength: 20,
strokeStyle: 'rgba(255, 255, 255, 0.5)',
type: 'sine'
},
{
timeModifier: 1,
lineWidth: 2,
amplitude: 150,
wavelength: 100,
strokeStyle: 'rgba(255, 255, 255, 0.3)'
}
],
initialize: function (){},
resizeEvent: function() {
var gradient = this.ctx.createLinearGradient(0, 0, this.width, 0);
gradient.addColorStop(0,"rgba(0, 0, 0, 0)");
gradient.addColorStop(0.5,"rgba(255, 255, 255, 0.5)");
gradient.addColorStop(1,"rgba(0, 0, 0, 0)");
var index = -1;
var length = this.waves.length;
while(++index < length){
this.waves[index].strokeStyle = gradient;
}
}
});
Easing
The default easing is Linear
which means the waves are not modified from left to right. Additionally you can specify one of the following easing functions to the waves to modify the amplitude of each wave throughout the width of the canvas.
Linear
SineIn
SineOut
SineInOut
Alternatively you can pass a function directly to the ease
option when creating a SineWaves instance.
ease: function(percent, amplitude) {
return amplitude * percent;
},
Wave Types
In addition to the default Sine wave can also generate, Square
, Sawtooth
, and Triangle
waves.
waves: [
{
type: 'Square'
segmentLength: 1,
},
{
type: 'Sawtooth'
segmentLength: 1,
},
{
type: 'Triangle'
segmentLength: 1,
}
],
Custom Waves
You can also specify your own wave function by supplying a function to the type parameter. This function has two arguments: x
and waves
. x
is the location of a point on the x axis and waves
a helper object with the following functions in it:
waves.sine(x)
waves.sign(x)
waves.square(x)
waves.sawtooth(x)
waves.triangle(x)
waves: [
{
timeModifier: 1,
lineWidth: 2,
amplitude: 150,
wavelength: 200,
segmentLength: 10,
strokeStyle: 'rgba(255, 255, 255, 0.5)',
type: function(x, waves) {
return Math.sin(x) * waves.sawtooth(x);
}
},
],
Examples on Codepen
Mobile
Canvas is supported on most devices however the due limited processing power complex animations may appear choppy. You can either create simplier animations for mobile or disable the animation by setting the running
property to false
. Running the update()
method will update the animation one frame while paused.
var waves = new SineWaves({
el: document.getElementById('waves'),
running: false,
waves: [{}]
});
waves.running = false;
waves.update();
License
SineWaves is open-sourced software licensed under the MIT license
Release History
- v0.3.0 - Refactor, added custom waves, and bug fixes
- v0.2.0-alpha - Added rotate, ease, wavesWidth and wave types options
- v0.1.0-alpha - Initial Release