How to make wave using jquery and html5 canvas

Few months back we’ve published how to give wave effect to your text using tweenmax.js. Today we’re gonna say, how you can create a wave without using any other plugin, with the help of simple jQuery and html5 canvas element. This tutorial is based of code snippets and very easy to understand. So let’s begin with our html file.

In html file

<div id="wave"></div>

Well, in your html you just need a div element, nothing else. And you also have to include the jQuery library as always.

Defining few variables

To make it easy editable, we will declare the necessary variables separately; so that only by making changes to those variables you can easily change the shape of your wave.

var wavelength= 200,
    amplitude= 60,
    phase= 90,
    width= 900,
    color= "green",
    thickness= 4;

var height = amplitude * 2;

We’ve defined and initialized few variables; similar to the basic properties of a wave. Height of a wave is always twice of its amplitude, so we’ve calculated the height here.

Make canvas and get context

This is the default step to start using html5 canvas. Hope it wont give you much pain to understand. Or you can learn about html5 canvas.

var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height =  height;

//get context
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);

Drawing the Wave

Let’s come to the main part now. All that you need to draw this wave, is mathematics. It’s all mathematical calculation here.

ctx.strokeStyle = color;
ctx.lineWidth = thickness;

phase = phase * Math.PI / 180;
var amp = amplitude – thickness / 2;
var freq = 2 * Math.PI * (1 / wavelength);
var yOrigin = height / 2;

var y1, y2;
for ( var i = 0; i < width; i++) { y1 = amp * Math.sin(phase + freq * i) + yOrigin; y2 = amp * Math.sin(phase + freq * (i + 1)) + yOrigin; ctx.moveTo(i , y1); ctx.lineTo(i + 1, y2); } ctx.stroke(); [/code] First of all, we've set the stroke style and line width as per our variables on top. After that, we've calculated the phase, ampere, frequency. Then simple wave mathematics. You can have a look on our preview or can download the project and do your analysis. live-demo-button download-button

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.

  • Nic

    Thanks… was searching for something like this… 🙂

  • priya

    i need an ecg waveform, how to make the wave run?

    • metalshan

      Priya, the example deals with uniform wave. I think ECG is a scattered wave. Either you can do modification in the “Drawing the Wave” paragraph logic or the best way is, using d3.js. D3 created graphs (including ecg type graphs) very easily with the data provided by you