1

市松模様のキャンバス背景を作るのに苦労しています。画面は現在、画面全体を塗りつぶす単色を表示しています。この色は、2 つのループelseの下にあるステートメントの fillStyleです。forモジュラス演算子の使い方が間違っていますか? それとも何か他のものですか?

function createBackground(){
        if(!Modernizr.canvas) return;

        var canvas = document.createElement('canvas'),
            context = canvas.getContext('2d'),
            background = $('#game .background')[0],
            rect = background.getBoundingClientRect(), //returns the dimension of background
            gradient,
            monsterSize = monstr.settings.monsterSize;

        canvas.width = rect.width;
        canvas.height = rect.height;
        context.scale(rect.width, rect.height);

        /* create checker */
        cols = canvas.width / monsterSize;
        rows = canvas.height / monsterSize;

        console.log(cols); //8
        console.log(rows); //12
        console.log(monsterSize); //40
        for (var i=0; i<cols; i++){
            for (var j=0; j<rows; j++){
                if((i+j)% 2){ /* for every other block */
                    context.fillStyle = '#262626';
                    context.fillRect(i*monsterSize, j*monsterSize, monsterSize, monsterSize);
                } else {
                    context.fillStyle = '#E8E8E8';
                    context.fillRect(i*monsterSize, j*monsterSize, monsterSize, monsterSize);
                }
            };
        };

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

1 に答える 1

2

キャンバスのスケーリングが間違っているため、チェッカーボード上のすべてのタイルが非常に大きくなり、画面に1つのタイルしか表示されません。

この行をコメントアウトします。

context.scale(rect.width, rect.height);

または、スケーリングが必要な場合でも、必要なスケーリングの量に応じて、渡した値を、、などの1小さな数値に置き換えてみてください。2

デモを参照してください。

于 2012-08-08T13:20:30.303 に答える