4

下面的代码为选取框设置动画。动画开始很快,但随着时间的推移明显减慢。请帮我弄清楚原因。相同的代码在这里: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();

4

1 回答 1

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

于 2012-04-19T18:17:18.650 回答