I am trying to draw a simple sine wave in a canvas but i am not getting it right. this is my desired output as in the picture.
What I have got so far is http://jsfid
Use bezierCurveTo
, this is only an example you should adjust parameters to get nice sinusoid
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;">
function plotSine(amplitude, frequency) {
const canvas = document.getElementById('canvas');
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.strokeStyle = '#343a40';
ctx.lineWidth = 2;
var x = 0;
var y = 0;
while (x < canvas.width) {
y = (canvas.height / 2) + amplitude * Math.sin(x / frequency);
ctx.lineTo(x, y);
x += 1;
}
ctx.stroke();
}
}
plotSine(40, 20);
code {
background-color: #eee;
border-radius: 3px;
padding: 0 3px;
}
<canvas id="canvas" width="480" height="360">
<p>
Your browser does not support the <code><canvas></code> element.
</p>
</canvas>