【问题标题】:How do I cut/clip a shape and reveal the shape behind it?如何剪切/剪辑形状并显示其背后的形状?
【发布时间】:2013-12-07 13:17:48
【问题描述】:

到目前为止,我得到了这个:http://jsfiddle.net/Lt7VN/

但是它剪切/剪切了红色和黑色的矩形,而我希望它只剪切黑色的矩形,我该怎么做呢?

context.beginPath();

context.rect(20,20,160,200);
context.fillStyle = "red";
context.fill();

context.beginPath();
context.rect(20,20,150,100);
context.fillStyle = "black";
context.fill();

context.globalCompositeOperation = "destination-out";

context.beginPath();
context.arc(100, 100, 50, 0, 2*Math.PI);
context.fill();

【问题讨论】:

  • 您始终可以将红色矩形绘制到另一个画布中,并将第二个画布放在顶部的下方。当然在这个具体的例子中,你可以完全省略globalCompositeOperation,只在矩形上画一个红色圆圈。
  • @akonsu 没有办法用一个画布来做吗?另外,画一个红色圆圈对我不起作用,因为我可能在黑色矩形而不是红色矩形下方使用多种颜色的图像或复杂的不规则形状。
  • 我不认为你可以用一张画布做到这一点。

标签: javascript html canvas globalcompositeoperation


【解决方案1】:

您可以使用合成在 1 个画布上执行此操作。

  • 绘制黑色矩形
  • 将合成设置为“擦除”的目的地输出
  • 绘制弧线(擦除部分黑色矩形)
  • 将合成设置为“落后”的目的地
  • 绘制红色矩形(填充在 arc-cut-rect 后面。

这是代码和小提琴:http://jsfiddle.net/m1erickson/F4dp3/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var context=canvas.getContext("2d");

    context.save();

    context.beginPath();
    context.rect(20,20,150,100);
    context.fillStyle = "black";
    context.fill();

    context.globalCompositeOperation = "destination-out";

    context.beginPath();
    context.arc(100, 100, 50, 0, 2*Math.PI);
    context.fill();

    context.globalCompositeOperation = "destination-over";

    context.beginPath();
    context.rect(20,20,160,200);
    context.fillStyle = "red";
    context.fill();

    context.restore();

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

【讨论】:

    【解决方案2】:

    我相信只有两幅画布 http://jsfiddle.net/Lt7VN/2/

    context1.globalCompositeOperation = 'destination-out';
    
    context1.beginPath();
    context1.arc(100, 100, 50, 0, 2*Math.PI);
    context1.globalAlpha = 1.0;
    context1.fill();
    

    【讨论】:

    • 如果我使用 KineticJS 会怎样?或者也许是与“destination-out”不同的方法?
    • KineticJS 使用多个画布。
    猜你喜欢
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多