2

我正在尝试使用画布运行动画背景。现在setTimeout显示 chrome 中的错误Uncaught SyntaxError: Unexpected identifier。我一定是动画错误。

当我删除setTimeout并拥有 时tiles(),一切正常(即没有动画,但显示我想要的正确背景)。所以我敢肯定,这与setTimeout.

有人给我线索吗?

function createBackground(){        
        var canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            background = $('#game .background')[0],
            rect = background.getBoundingClientRect(), //returns the dimension of background
            gradient,
            m = monster.settings.monsterSize;

        canvas.width = rect.width;
        canvas.height = rect.height;

        /* create checker */
        tile_cols = canvas.width / m;
        tile_rows = canvas.height / m;

        setTimeout(tiles(ctx, m, tile_cols, tile_rows), 300);

        /* add canvas to html element */
        background.appendChild(canvas); 
    }

    function tiles(ctx, m, tile_cols, tile_rows){
        for (var i=0; i<tile_cols; i++){
            for (var j=0; j<tile_rows; j++){
                var x = Math.ceil(Math.random()*3);

                switch(x){
                    case 1:
                        ctx.fillStyle = 'black';
                        break;

                    ....

                    case 3:
                        ctx.fillStyle = '#00080E';
                        break;  
                }

                ctx.strokeStyle = 'black';
                ctx.beginPath(); 
                ...
                ctx.closePath();

                ctx.fill();
                ctx.stroke();

            };
        };      

        return this;
    }
4

1 回答 1

4

您将结果分配tiles(ctx, m, tile_cols, tile_rows)给第一个参数setTimeout

将其更改为

setTimeout(function() {
    tiles(ctx, m, tile_cols, tile_rows)
}, 300);

你应该看看requestAnimationFrame这个任务。Paul Irish 写了一篇关于它的好文章

于 2012-08-23T08:51:54.683 回答