# Drawing a sine wave on canvas

I am trying to draw a simple sine wave on a canvas, but I don't get it. this is my desired result as in the picture.

So far I got http://jsfiddle.net/RaoBurugula/gmhg61s6/4/

Html

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

```

Js

`````` var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i;
for(i=0; i<360; i+= 20){
ctx.moveTo(i+5,180);
ctx.lineTo(i,180);

}
ctx.stroke();
var counter = 0, x=0,y=180;

//100 iterations
var increase = 90/180*Math.PI ;
for(i=0; i<=180; i+=10){

ctx.moveTo(x,y);
x = i;
y=  180 - Math.sin(counter);
counter += increase;

ctx.lineTo(x,y);
alert( " x : " + x + " y : " + y) ;
}
ctx.stroke();
```

```

My desired result

+3

source to share

You increase `counter`

with too much value, decrease it:

``````var increase = 90/180*Math.PI / 9;
```

```

Draw the entire width of the chart instead of half:

``````for(i=0; i<=360; i+=10){
```

```

You need a higher amplitude:

``````y =  180 - Math.sin(counter) * 120;
```

```
+3

source

Your code is unnecessarily complex. Try it this simple:

``````var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

for(x=0; x<360; x += 20){
ctx.moveTo(x+5,180);
ctx.lineTo(x,180);
}
ctx.moveTo(0,180);

for(x=0; x<=360; x+=1){
y = 180.0 - Math.sin(x*Math.PI/180)*120;
ctx.lineTo(x,y);
}
ctx.stroke();
```

```
+1

source

``````<pre>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i;
var amplitude=90;
var width=c.width;
var xAxis=300;
var step=1;
var frequency=4;
ctx.moveTo(0,250);
ctx.lineTo(width,250);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0,250);
var c=width/Math.PI/(frequency*2);
for(i=0; i<width; i+=step){
var x = amplitude * Math.sin(i /c);
ctx.lineTo(i,250+x);

}
ctx.strokeStyle = '#0096FF';

ctx.stroke();
</pre>
```

```
+1

source

Use `bezierCurveTo`

, this is just an example you should tweak the parameters to get a nice sine wave

``````var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(50,50);
ctx.bezierCurveTo(120,-100,200,250,250,50);
ctx.bezierCurveTo(300,-100,350,250,430,50);
ctx.lineWidth = 5;
ctx.strokeStyle = '#003300';
ctx.stroke();```

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

```
Hide result

+1

source

With Single loop, you can easily

``````var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var y=180;
//draw axis
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.moveTo(0,  y/2);
ctx.lineTo(y,  y/2);
ctx.stroke();
// draw sin wave
ctx.beginPath();
ctx.moveTo(x,y);
ctx.strokeStyle = "black";
for(var x=0; x<=180; x+=1){
ctx.lineTo(x,((y/2)  + y/2  * Math.sin( ((x+-y/2)/90) * Math.PI)));
ctx.stroke();
}```

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

```
Hide result

0

source

All Articles