Reputation: 23
<!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...?
Upvotes: 0
Views: 38
Reputation: 12891
Let me cite the following paragraph out of Compositing and clipping over at developer.mozilla.org:
globalCompositeOperation = type This sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compositing operations to use.
The key here is: '...when drawing new shapes...'
So changing the composite operation for your canvas as the last command in the drawing chain doesn't affect shapes drawn priorly.
Upvotes: 1