【问题标题】:Clipping region is not cleared by restore()restore() 不会清除剪辑区域
【发布时间】:2015-11-22 14:33:51
【问题描述】:

我正在尝试绘制剪切到区域 1 的 shape1 和剪切到区域 2 的 shape2。我的自然假设是,以下内容会得到我想要的效果。

context.save();
context.clip(region1);
context.fill(shape1);
context.restore();

context.save();
context.clip(region2);
context.fill(shape2);
context.restore();

但是,令我惊讶的是,第一个 restore() 并没有取消当前的剪辑区域。相反,第二个区域与第一个区域相结合。这与多个在线资源声称 restore() 是完成剪辑后的最佳选择相反。

Live example。可以看到第二个填充(蓝色)被裁剪到 region1+region2,而不仅仅是 region2。

更奇怪的是,这种附加行为是通过使用save/restore 调用来实现的。如果我放弃它们,第二个 clip 呼叫将被忽略。

所以,我有两个问题。

  1. 在 html5 画布中剪辑的工作方式有什么逻辑吗?
  2. 我怎样才能完成我最初打算做的事情?

感谢任何帮助解决这个问题!

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

    始终以context.beginPath() 开始绘制新路径。

    否则会导致之前的所有绘图命令与新添加的命令一起重新执行。

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    ctx.save();
    ctx.beginPath();
    ctx.rect(100, 0, 100, 300);
    ctx.clip();
    ctx.fillStyle = "lime";
    ctx.fillRect(0,0,300,300);
    ctx.restore();
    
    
    ctx.save();
    ctx.beginPath();
    ctx.rect(50, 50, 200, 200);
    ctx.clip();
    ctx.fillStyle = "blue";
    ctx.fillRect(0,0,300,300);
    ctx.restore();
    body{ background-color: ivory; }
    #canvas{border:1px solid red; margin:0 auto; }
    <canvas id="canvas" width=300 height=300></canvas>

    【讨论】:

    • 非常感谢!我已经使用 canvas 很长时间了,但不知道 'rect(...)' 调用不是独立的!
    猜你喜欢
    • 2014-08-02
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 2011-08-04
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多