2012-04-19 147 views
3

下面的代碼動畫了一個選框行。動畫開始的速度非常快,但隨着時間的推移顯着減慢。請幫我弄清楚爲什麼。相同的代碼在這裏:http://jsbin.com/aleqef/畫布動畫放慢

編輯:我沒有創建任何新的對象,在我的動畫循環期間,一切似乎都被緩存,即模式,上下文等。我只是沒有看到任何可疑的東西。看起來像一個記憶問題,但我不知道爲什麼。

 
var data = [ 
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAMAAADXEh96AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAAGUExURQAAAP///6XZn90AAAAcSURBVHjaYmBgYGBkZAQSYAjlgUXgYhAeQIABAAGkABPpfLrFAAAAAElFTkSuQmCC", 
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAMAAADXEh96AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAAGUExURQAAAP///6XZn90AAAAeSURBVHjaYmBkAEEgYGRkBBEgFgMDRBTGA8sBBBgAAaQAE03fiAgAAAAASUVORK5CYII=", 
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAMAAADXEh96AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAAGUExURQAAAP///6XZn90AAAAdSURBVHjaYmBgZGRkYGAAY0YGCITxoHIQUYAAAwABpAATvSsONQAAAABJRU5ErkJggg==" 
];
var context = document.getElementById("canvas").getContext("2d"); var count = data.length; var patterns = []; var pattern = 0;
function onload(e) { patterns.push(context.createPattern(e.target, "repeat")); }
function draw() { for (var angle = 0; angle < 360; angle += 5) { var rad = (angle * Math.PI)/180; var x = 200 * Math.cos(rad); var y = 200 * Math.sin(rad);
context.moveTo(0, 0); context.lineTo(x, y); } }
function animate() { window.setTimeout(animate, 1000/60);
if (patterns.length > 0) { context.clearRect(0, 0, context.canvas.width, context.canvas.height); draw(); context.lineWidth = 1; context.strokeStyle = patterns[pattern]; context.stroke(); pattern = (pattern + 1) % patterns.length; } }
for (var i = 0; i < count; i++) { var image = new Image(); image.onload = onload; image.src = data[i]; }
animate();

+0

您曾經試圖弄清楚自己爲什麼?那導致你在哪裏? – Armatus 2012-04-19 17:54:28

+0

我有和失敗:)特別是,我不看我是否在我的動畫循環過程中創建任何新的對象,似乎一切都緩存,即模式,上下文等。 – akonsu 2012-04-19 17:56:04

+0

不用擔心。你知道多麼陰暗的「請幫我弄清楚爲什麼」,然後是一個大的代碼塊,看起來沒有你給的細節:) – Armatus 2012-04-19 18:03:30

回答

4

試試這個變化(beginPath方法())

if (patterns.length > 0) { 
    context.clearRect(0, 0, context.canvas.width, context.canvas.height); 
    context.beginPath(); 
    draw(); 

鏈接http://jsbin.com/aleqef/4/edit#preview

+0

這太棒了。謝謝。你知道爲什麼beginPath似乎可以解決這個問題嗎? – akonsu 2012-04-19 18:19:36

+1

答案在這裏:) http://stackoverflow.com/a/4983173/1238040 – 2012-04-19 18:20:43