1

到目前为止,我得到了这个: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();
4

2 回答 2

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>
于 2013-11-22T16:39:37.697 回答
0

两张画布是我相信的唯一方法 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();
于 2013-11-22T16:20:08.053 回答