Calculator Collection | About the Calculator Series | Inside the Code | Home

Draw a Sine Wave on the Canvas

Enter the amplitude, frequency and phase of your sine wave, along with the display parameters. The JavaScript code draws the sine wave on the canvas.

Vp (V) Peak Voltage
fo (Hz) Sine frequency
Phase (deg) Time Shift
Vmax (V) for plot
Tmax (s) for plot
Npoints for plot

Download / Basics

To run or modify on your PC, download a simple version of this file.
For a quick tour of some JavaScript / HTML basics, check out Inside the Code.

JavaScript

Drawing a sine wave stands on the JavaScript shoulders of the Drawing a Rectangle example. The sine parameters are entered in the time and volts domain. The code transforms the time and volts coordinates into x and y pixel coordinates on the canvas.

Two subroutines are called: one to draw the axes (ShowAxes) and the other to draw the sine function (GraphArray). The first routine ShowAxes( ) draws a horizontal and a vertical line through the center of the canvas. The variables x0 and y0 define the center using x0 = 0.5 x w (width of canvas) and y0 = 0.5 x h (height of canvas).

 ctx.moveTo(0,y0);    ctx.lineTo(w,y0);  // X axis
ctx.moveTo(x0,0);    ctx.lineTo(x0,h);  // Y axis

Next, the time and voltage axes needs to be transformed into x and y pixel coordinates. How? The code calculates scaling factors using the entered maximum voltage (Vmax) and time (Tmax) to be plotted.

 axes.xscale = (canvas.width)/(2*Tmax); // x pix per s
axes.yscale = (canvas.height)/(2*Vmax); // y pix per V

The time increment dT is easly calculated given the number of display points N.

 tstart = -Tmax;
tstop = Tmax;
dt = (tstop - tstart) / (N-1);

Now. the code creates the sine function and stores it (along with the time axis) in array variables x and y.

for ( i=0; i<N; i++) {
   x[i]=tstart + i*dt;
   y[i] = Vp*Math.sin(2*3.1415*fo*x[i] + phase*3.1415/180) ;
}

Finally, how do we get our time (x) and voltage (y) values onto the canvas? The x and y arrays are passed to the function GraphArray( ). The heart of the code first translates the x,y function coordinates to the xp, yp pixel coordinates, and then uses the lineTo function to draw a line to the next pixel coordinate.

for (i=0; i<axes.N; i++) {
  // translate actual x,y to plot xp,yp
  xp = x0 + x[i]*xscale;
  yp = y0 - y[i]*yscale;

  // draw line to next point
  if (i==0) ctx.moveTo( xp, yp );
  else ctx.lineTo( xp, yp );
}

HTML

The heart of the HTML is the canvas tag.

<canvas id="canvas" width="501" height="201"></canvas>

which defines it's reference ID for use in the JavaScript code and its dimensions.