在画布上绘制正弦波 [英] drawing sine wave in canvas

查看:171
本文介绍了在画布上绘制正弦波的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在画布上绘制一个简单的正弦波,但我没有把它做好。这是我期望的输出,如图中所示。



到目前为止,我得到的是


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://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 output

解决方案

You are increasing counter with a value that it too high, make it smaller:

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

Draw the whole width of the diagram instead of half:

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

You need a higher amplitude:

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

Demo: http://jsfiddle.net/Guffa/gmhg61s6/5/

这篇关于在画布上绘制正弦波的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆