Canvas How to - Draw sin function








Question

We would like to know how to draw sin function.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--   w  w w.j  a  v a 2s.  c  o  m-->
var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),
    width = 400;
    context.strokeStyle = 'red';
    canvas.width = 400;

    var render = function() {
        context.strokeStyle = 'red';
        var t = new Date().getTime();
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.fillStyle = 'black';
        context.fillRect(0, 0, canvas.width, canvas.height);
        for (var m = 1; m < 5; m++) {
        context.beginPath();
        for (var x = 0; x < canvas.width; x++) {
            var halfHeight = canvas.height/2,
                y = Math.sin((t * m)/500 + x/10)*halfHeight + halfHeight;
            context.lineTo(x, y);
        }
        context.stroke();
        }
    };
    var animate = function() {
        render();
        window.requestAnimationFrame(animate);
    };
    animate();
}//]]>  
</script>
</head>
<body>
  <div>
    <canvas id="canvas" />
  </div>
</body>
</html>

The code above is rendered as follows: