2011-05-17 80 views
4

我正在编写一个程序,用画布绘制sine curve
HTML:如何绘制一条可以通过画布向左移动的曲线?

<canvas id="mycanvas" width="1000" height="100"> 
    Your browser is not supported. 
</canvas> 

的JavaScript:

var canvas = document.getElementById("mycanvas"); 
if (canvas.getContext) { 
    var ctx = canvas.getContext("2d"); 
    ctx.lineWidth = 3; 
    var x = 0, 
     y = 0; 
    var timeout = setInterval(function() { 
     ctx.beginPath(); 
     ctx.moveTo(x, y); 
     x += 1; 
     y = 50 * Math.sin(0.1 * x) + 50; 
     ctx.lineTo(x, y); 
     ctx.stroke(); 
     if (x > 1000) { 
      clearInterval(timeout); 
     } 
    }, 10); 
} 

这工作真的很好:http://jsfiddle.net/HhGnb/

不过,现在我只能提供说100像素的画布宽度,所以只有最左边100像素曲线可以被看到。 http://jsfiddle.net/veEyM/1/
我想存档这个效果:当曲线的右边的点大于画布的宽度时,整条曲线可以向左移动,所以我可以看到曲线的最右点,这有点像曲线流向左边。我可以这样做吗?

+0

这是棘手的,因为画布不记得你画什么,而像素的颜色。您每次都需要重新绘制整个图像。所以我会保存你计算的所有分数并与他们一起工作。 – pimvdb 2011-05-17 15:18:44

+0

赞:http://jsfiddle.net/veEyM/2/。 – pimvdb 2011-05-17 15:23:05

+0

@pimvdb这很好,你可以发布一个答案与代码的一些解释? – wong2 2011-05-17 15:27:08

回答

11

<canvas>元素的基本思想之一是计算机'忘记'绘图命令,只保存像素,就像位图一样。因此,要将所有内容移到左侧,您需要清除画布并再次绘制所有内容。

我还想告诉你一件事 - 你总是以x = 0和y = 0开始,但显然在x = 0时y不一定等于0。编辑:实现了这一点。

不管怎样,我结束了这段代码:http://jsfiddle.net/veEyM/5/

var canvas = document.getElementById("mycanvas"); 
var points = {}; // Keep track of the points in an object with key = x, value = y 
var counter = 0; // Keep track when the moving code should start 

function f(x) { 
    return 50 * Math.sin(0.1 * x) + 50; 
} 

if (canvas.getContext) { 
    var ctx = canvas.getContext("2d"); 
    ctx.lineWidth = 3; 
    var x = 0, 
     y = f(0); 
    var timeout = setInterval(function() { 
     if(counter < 100) { // If it doesn't need to move, draw like you already do 
      ctx.beginPath(); 
      ctx.moveTo(x, y); 
      points[x] = y; 
      x += 1; 
      y = f(x); 
      ctx.lineTo(x, y); 
      ctx.stroke(); 
      if (x > 1000) { 
       clearInterval(timeout); 
      } 
     } else { // The moving part... 
      ctx.clearRect(0, 0, 100, 100); // Clear the canvas 
      ctx.beginPath(); 
      points[x] = y; 
      x += 1; 
      y = f(x); 
      for(var i = 0; i < 100; i++) { 
       // Draw all lines through points, starting at x = i + (counter - 100) 
       // to x = counter. Note that the x in the canvas is just i here, ranging 
       // from 0 to 100 
       ctx.lineTo(i, points[i + counter - 100]); 
      } 
      ctx.stroke(); 
     } 
     counter++; 
    }, 10); 
}