title: Animating sine wave in js
body: <p>I'm trying to animate a sine wave in JS but it's not acting as expected. I'm using a <code>&lt;canvas&gt;</code> element along with <code>window.requestAnimationFrame()</code> method but it's a CPU hog and as i change frequency with the slider it just break and show random waveforms. I also don't know if drawing adjacent lines is the best way to represent a sine wave. Please note that i'll use vanilla JS and that the sine's frequency and amplitude are variables set by sliders. Thanks in advance.</p>
  
  <p>This is what i got so far: <a href="http://cssdeck.com/labs/8cq5vclp" rel="nofollow noreferrer">http://cssdeck.com/labs/8cq5vclp</a></p>
  
  <p><strong>UPDATE:</strong> i worked on it and this is the new version: <a href="http://cssdeck.com/labs/sbfynjkr" rel="nofollow noreferrer">http://cssdeck.com/labs/sbfynjkr</a></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas = document.querySelector("canvas"),
    ctx = canvas.getContext("2d"),
    cHeight = canvas.height,
    cWidth = canvas.width,
    frequency = document.querySelector("#f").value,
    amplitude = 80,
    x = 0,
    y = cHeight / 2,
    point_y = 0;
  
  window.onload = init;
  
  function init() {
    document.querySelector("#f").addEventListener("input", function() {
      frequency = this.value;
      document.querySelector("#output_f").value = frequency;
    }, false);
  
    drawSine();
  }
  
  function drawSine() {
    ctx.clearRect(0, 0, cWidth, cHeight);
  
    ctx.beginPath();
    ctx.moveTo(0, y);
    ctx.strokeStyle = "red";
    ctx.lineTo(cWidth, y);
    ctx.stroke();
    ctx.closePath();
  
    ctx.beginPath();
    ctx.strokeStyle = "black";
    for (x = 0; x &lt; 600; x++) {
      point_y = amplitude * -Math.sin((frequency / 95.33) * x) + y;
      ctx.lineTo(x, point_y);
    }
    ctx.stroke();
    ctx.closePath();
    requestAnimationFrame(drawSine);
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
    border: 1px solid red;
    margin: 10px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input id="f" type="range" min="0" max="20000" value="20" step="1"&gt;
  &lt;output for="f" id="output_f"&gt;20&lt;/output&gt;
  &lt;canvas width="600px" height="200px"&gt;&lt;/canvas&gt;</code></pre>
  </div>
  </div>
  </p>