draw a 2d sine wave in javascript

Here's an example of how to draw a 2D sine wave in JavaScript using HTML5 canvas.

<!DOCTYPE html>
<html>
  <head>
    <title>2D Sine Wave</title>
  </head>
  <body>
    <canvas id="canvas" width="800" height="300"></canvas>
    <script>
      var canvas = document.getElementById('canvas');
      var ctx = canvas.getContext('2d');
      var x = 0;
      var y = canvas.height/2;

      // Set up the animation loop
      function draw() {
        requestAnimationFrame(draw);

        // Clear the canvas for each frame
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // Draw the sine wave
        ctx.beginPath();
        ctx.moveTo(x, y);
        for (var i = 0; i < canvas.width; i++) {
          x = i;
          y = Math.sin(x/20) * 50 + canvas.height/2;
          ctx.lineTo(x, y);
        }
        ctx.strokeStyle = 'blue';
        ctx.stroke();
      }

      // Start the animation loop
      draw();
    </script>
  </body>
</html>
881 chars
38 lines

In this code, we first set up the canvas and get its 2D graphics context. We then define the starting position of the wave and set up an animation loop using requestAnimationFrame(). Each frame of the animation, we clear the canvas and draw the sine wave by iterating over each x-coordinate from 0 to the width of the canvas and calculating the corresponding y-coordinate using the sine function. Finally, we set the stroke style to blue and draw the line using ctx.stroke().

gistlibby LogSnag