javascript - 单击按钮后,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...?
解决方案
让我从 developer.mozilla.org上的Compositing and clipping中引用以下段落:
globalCompositeOperation = type 这设置了在绘制新形状时应用的合成操作的类型,其中 type 是一个字符串,用于标识要使用的十二个合成操作中的哪一个。
这里的关键是:'......绘制新形状时......'
因此,将画布的合成操作更改为绘图链中的最后一个命令不会影响先前绘制的形状。
推荐阅读
- android - 在 android/Xamarin.Android 中单击通知时切换到正在运行的活动
- java - 使用 Java 流从集合中获取两个最小对象
- node.js - 当值不在数组中时,猫鼬 findOneAndUpdate
- makefile - 在 CMAKE for Protobuf 中使用 distcc 时未定义的引用
- java - 具有连接表的单个实体上的多对多
- arrays - JSONata 按数组排序/排序
- python - 如何在 pandas python 中转换 11:54 的 1154 时间格式?
- ios - AVVideoCompositionCoreAnimationTool 中的 CALayer 实时模糊
- linux - 需要在 windows korn shell 中运行 ksh 脚本
- python - 使用 Python 生成所有组合