繁体   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