2011-05-17 81 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); 
}