Sine Wave Demo

HTML5 canvas demos

by wnaylor

HTML

<canvas id="myCanvas" width="500" height="200" />

JavaScript

$(document).ready(function() {
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');

  sinPath(ctx);
});

function sinPath(ctx) {
  var n = 100;
  var dx = 2 * (Math.PI) / n;
  var x = 0.00001;
  var px = 10;
  var py = 100;

  ctx.beginPath();
  ctx.moveTo(px, py);

  for (var i = 0; i < n; i++) {
    x += dx;
    y = Math.sin(x);

    px += (180.0 / (Math.PI)) * dx;
    py = 100 - 80 * y;

    ctx.lineTo(px, py);
  }

  ctx.stroke();
  ctx.closePath();
}