画布正弦波方向

时间:2019-06-06 08:03:28

标签: javascript canvas

我试图在画布上绘制一个简单的正弦波,但是我无法将动画的方向更改为垂直(从上到下)。告诉我该怎么做?

JavaScript代码

var c = document.getElementById('canv');
var $ = c.getContext('2d');

var w = c.width = window.innerWidth;
var h = c.height = window.innerHeight;

var lineOffset = 60;

var draw = function(a, b, t) {

  $.clearRect(0, 0, w, h);
  $.lineWidth = 0.2;

  for (var i = -70; i < 70; i += 1) {
    $.strokeStyle = 'red';
    $.beginPath();
    $.moveTo(0, h / 2);
    
    for (var j = 0; j < w; j += 10) {
      $.lineTo(lineOffset * Math.sin(i / 10) +
        j + 0.008 * j * j,
        Math.floor(h / 2 + j / 2 *
          Math.sin(j / 50 - t / 50 - i / 118) +
          (i * 0.9) * Math.sin(j / 25 - (i + t) / 65)));
    };

    $.stroke();
  }

}
var t = 0;

var run = function() {
	window.requestAnimationFrame(run);
	t += 2;
	draw(33, 52 * Math.sin(t / 2400), t);
};
run();
<canvas id='canv'></canvas>

1 个答案:

答案 0 :(得分:2)

在draw函数中,我用w更改了w,反之亦然。

我已将$.moveTo(0,h / 2)更改为$.moveTo(w / 2,0);

在for循环中,我将x的值更改为y的值,反之亦然。

我希望这是您所需要的。

var c = document.getElementById('canv');
var $ = c.getContext('2d');

var w = c.width = window.innerWidth;
var h = c.height = window.innerHeight;

var lineOffset = 60;

var draw = function(a, b, t) {

  $.clearRect(0, 0, w, h);
  $.lineWidth = 0.2;

  for (var i = -70; i < 70; i += 1) {
    $.strokeStyle = 'red';
    $.beginPath();
    $.moveTo(w / 2,0);
    
    
    /*
    for (var j = 0; j < w; j += 10) {
      $.lineTo(lineOffset * Math.sin(i / 10) +
        j + 0.008 * j * j,
        Math.floor(h / 2 + j / 2 *
          Math.sin(j / 50 - t / 50 - i / 118) +
          (i * 0.9) * Math.sin(j / 25 - (i + t) / 65)));
    };
    */
    
    for (var j = 0; j < h; j += 10) {
      let y = lineOffset * Math.sin(i / 10) +
        j + 0.008 * j * j;
      
      let x = Math.floor(w / 2 + j / 2 *
          Math.sin(j / 50 - t / 50 - i / 118) +
          (i * 0.9) * Math.sin(j / 25 - (i + t) / 65))
      $.lineTo(x,y);
    };
    
    

    $.stroke();
  }

}
var t = 0;

var run = function() {
	window.requestAnimationFrame(run);
	t += 2;
	draw(33, 52 * Math.sin(t / 2400), t);
};
run();
<canvas id='canv'></canvas>