소프트웨어, 수학 자료 정리

자바스크립트 캔버스를 이용하여 사인파 그리기

소스 코드

<canvas id="myCanvas" width="360" height="400" style="border:1px solid #d3d3d3;">

Your browser does not support the canvas element.

</canvas>


<script>


var c = document.getElementById("myCanvas");

var ctx = c.getContext("2d");


// X축 그리기

for(x=0; x<360; x += 20){

    ctx.moveTo(x+5,180);

    ctx.lineTo(x,180);

}


// 청색 사인파 그리기

ctx.moveTo(0,180);

ctx.strokeStyle="blue";

for(x=0; x<=360; x+=1){

    y = 180.0 - Math.sin(x*Math.PI/180)*120;

    ctx.lineTo(x,y);

}

ctx.stroke();


// 적색 사인파 그리기

ctx.beginPath();

ctx.moveTo(0,180);

ctx.strokeStyle="red";

for(x=0; x<=360; x+=1){

    y = 180.0 - Math.sin(2*x*Math.PI/180)*120;

    ctx.lineTo(x,y);

}



ctx.stroke();


</script>



<실행결과>

Your browser does not support the canvas element.



참고: https://stackoverflow.com/questions/29917446/drawing-sine-wave-in-canvas