简体   繁体   English

了解HTML5 Canvas元素

[英]Understanding HTML5 Canvas Element

I am read tons of documentation about save/restore canvas states, but still confused with next example . 我阅读了大量有关保存/恢复画布状态的文档,但是仍然与下一个示例混淆。

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

My logic in code comments, but result absolutely not expected. 我在代码注释中的逻辑,但是绝对没有预期的结果。 First circle has a settings from line. 第一个圆具有从线开始的设置。 Circles should have different style from line. 圆与线的样式应不同。

I am not good at canvas just yet but with some basic learning I think You are missing ctx.beginPath(); 我目前还不太擅长使用画布,但是通过一些基础学习,我认为您缺少ctx.beginPath(); before starting to draw path. 在开始绘制路径之前。

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 DEMO

SOURCE 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM