1

キャンバスの状態の保存/復元に関するドキュメントをたくさん読んでいますが、まだ次のと混同しています。

function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');

    // save default state
    ctx.save();

    // draw new arc with new settings
    ctx.lineWidth = 2;
    ctx.fillStyle = '#bfb';
    ctx.strokeStyle = '#999';
    ctx.beginPath();
    ctx.arc(50, 50, 10, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    // restore default state
    ctx.restore();

    // save default state again
    ctx.save();
    // draw line with new settings
    ctx.lineWidth = 4;
    ctx.strokeStyle = '#000';
    ctx.moveTo(50, 50);
    ctx.lineTo(100, 100);
    ctx.stroke();
    // restore default state
    ctx.restore();

    // save default state third time
    ctx.save();
    // draw round circle with new settings
    ctx.beginPath();
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#999';
    ctx.arc(100, 100, 10, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.fillStyle = '#bfb';
    ctx.fill();
    ctx.stroke();
    // restore default state
    ctx.restore();
}

draw();

コードコメントの私のロジックですが、結果はまったく期待できません。最初の円は線からの設定があります。円は線とは異なるスタイルにする必要があります。

4

1 に答える 1

1

私はまだキャンバスが得意ではありませんが、いくつかの基本的な学習で、 ctx.beginPath();パスを描き始める前にあなたが欠けていると思います.

function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');

    // save default state
    ctx.save();

    // draw new arc with new settings
    ctx.lineWidth = 2;
    ctx.fillStyle = '#bfb';
    ctx.strokeStyle = '#999';
    ctx.beginPath();
    ctx.arc(50, 50, 10, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    // restore default state
    ctx.restore();

    // save default state again
    ctx.save();
    // draw line with new settings
    ctx.beginPath();
    ctx.lineWidth = 4;
    ctx.strokeStyle = '#000';
   ctx.moveTo(50, 50);
     ctx.lineTo(100, 100);
    ctx.stroke();
    // restore default state
   ctx.restore();

    // save default state third time
    ctx.save();
    // draw round circle with new settings
    ctx.beginPath();    /* ** THIS is missing in your code ** */
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#999';
    ctx.arc(100, 100, 10, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.fillStyle = '#bfb';
    ctx.fill();
    ctx.stroke();
    // restore default state
    ctx.restore();
}

draw();

デモ

ソース

于 2013-05-22T05:47:35.420 に答える