Canvas Compositor Demonstration
<!DOCTYPE html> <html> <head> <title>Canvas Demo</title> <style> canvas { //from w w w . java 2s . c om border: 1px solid #000; } </style> </head> <body> <canvas id="myCanvas" width="200" height="200">Did You Know: Every time you use a browser that doesn't support HTML5 </canvas> <br> <select id="compositor"> <option value="source-over" selected>source-over</option> <option value="destination-atop">destination-atop</option> <option value="destination-in">destination-in</option> <option value="destination-out">destination-out</option> <option value="destination-over">destination-over</option> <option value="source-atop">source-atop</option> <option value="source-in">source-in</option> <option value="source-out">source-out</option> <option value="copy">copy</option> <option value="lighter">lighter</option> <option value="xor">xor</option> </select> <button id="toggle-triangle">Toggle Triangle</button> <script> let myCanvas = document.getElementById('myCanvas'); let myContext = myCanvas.getContext('2d'); let mySelector = document.getElementById('compositor'); let toggleTriangle = document.getElementById('toggle-triangle'); function drawExample() { myContext.globalCompositeOperation = 'source-over'; myContext.clearRect(0, 0, 200, 200); myContext.beginPath(); // Draw the circle first. myContext.arc(60, 100, 40, 0, 7); myContext.fillStyle = '#ff0000'; myContext.fill(); myContext.globalCompositeOperation = mySelector.value; myContext.beginPath(); myContext.fillStyle = '#0000ff'; myContext.rect(60, 60, 80, 80); myContext.fill(); } let showTriangle = false; function showHideTriangle() { if (showTriangle) { myContext.fillStyle = '#00ff00'; myContext.beginPath(); myContext.moveTo(40, 80); myContext.lineTo(170, 100); myContext.lineTo(40, 120); myContext.lineTo(40, 80); myContext.fill(); } else { drawExample(); } } drawExample(); mySelector.addEventListener('change', function() { showTriangle = false; drawExample(); }, false); toggleTriangle.addEventListener('click', function() { showTriangle = showTriangle ? false : true; showHideTriangle(); }, false); </script> </body> </html>