首页 > 解决方案 > 单击按钮后,globalCompositeOperation 无法正常工作......我怎样才能获得作为第二个画布的预期答案?

问题描述

<!DOCTYPE html>
<html>
<head>
  <title>Compositing Canvas</title>
</head>
<body>

  <canvas id="canvas1" width="200" height="200" style="border: 1px solid"></canvas> <br>

  <button onclick="composite()">Composite</button> <br>

  <p>Result Should be : </p>
  
  <canvas id="canvas2" width="200" height="200" style="border: 1px solid"></canvas>

  <script type="text/javascript">

    // 1st Canvas

    let canvas1 = document.getElementById('canvas1');
    let ctx1 = canvas1.getContext('2d');
    ctx1.fillStyle = "red";
    ctx1.fillRect(10, 10, 100, 100);

    // globalCompositeOperation = "source-over|source-atop|source-in|source-out|destination-over|destination-atop|destination-in|destination-out|lighter|copy|xor"
    function composite() {
      ctx1.globalCompositeOperation = "source-atop";
    };

    ctx1.fillStyle = "blue";
    ctx1.arc(110, 110, 80, 0 * Math.PI, 2 * Math.PI);
    ctx1.fill();

    // 2nd Canvas

    let canvas2 = document.getElementById('canvas2');
    let ctx2 = canvas2.getContext('2d');
    ctx2.fillStyle = "red";
    ctx2.fillRect(10, 10, 100, 100);

    ctx2.globalCompositeOperation = "source-atop";

    ctx2.fillStyle = "blue";
    ctx2.arc(110, 110, 80, 0 * Math.PI, 2 * Math.PI);
    ctx2.fill();

  </script>
  <br/>
</body>
</html>

After clicking the button, the globalCompositeOperation is not working...how can i do that for the expected answer?
the expected answer is in the second Canvas or second image...
why it is not working...?

标签: javascripthtml5-canvas

解决方案


让我从 developer.mozilla.org上的Compositing and clipping中引用以下段落:

globalCompositeOperation = type 这设置了在绘制新形状时应用的合成操作的类型,其中 type 是一个字符串,用于标识要使用的十二个合成操作中的哪一个。

这里的关键是:'......绘制形状时......'

因此,将画布的合成操作更改为绘图链中的最后一个命令不会影响先前绘制的形状。


推荐阅读