drawing sine wave in canvas

后端 未结 8 1945
情书的邮戳
情书的邮戳 2020-12-29 14:43

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

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 15:30

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var i;
    var amplitude = 90;
    var width = c.width;
    var height = c.height / 2;
    var step = 1;
    var frequency = 4;
    ctx.moveTo(0, height);
    ctx.lineTo(width, height);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(0, height);
    var c = width / Math.PI / (frequency * 2);
    
    for (i = 0; i < width; i += step) {
      var x = amplitude * Math.sin(i / c);
      ctx.lineTo(i, height + x);
    }
    
    ctx.strokeStyle = '#0096FF';
    ctx.stroke();

提交回复
热议问题