drawing sine wave in canvas

后端 未结 8 1944
情书的邮戳
情书的邮戳 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:37

    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;">

    0 讨论(0)
  • 2020-12-29 15:39

    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>&lt;canvas&gt;</code> element.
      </p>
    </canvas>

    0 讨论(0)
提交回复
热议问题