簡體   English   中英

了解HTML5 Canvas元素

[英]Understanding HTML5 Canvas Element

我閱讀了大量有關保存/恢復畫布狀態的文檔,但是仍然與下一個示例混淆。

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();

我在代碼注釋中的邏輯,但是絕對沒有預期的結果。 第一個圓具有從線開始的設置。 圓與線的樣式應不同。

我目前還不太擅長使用畫布,但是通過一些基礎學習,我認為您缺少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();

DEMO

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM