刮刮卡(圖片合成)javascript
將 myCanvas 的背景圖設置爲一張圖片,(刮開後顯示)css
// 目標圖像(已有的,外面一層即將被刮掉的那一圖像)html
pen.beginPath();java
pen.fillStyle = "red";canvas
pen.fillRect(100, 300, 100, 100);瀏覽器
// pen.globalCompositeOperation = "source-over"; / / 默認值,能夠理解爲 目標圖像 層級高於 源圖像
app
// pen.globalCompositeOperation = "source-atop"; // 目標圖像之外 的 源圖像 是透明的flex
// pen.globalCompositeOperation = "source-in"; // 只有目標圖像之內的源圖像顯示,其餘部分圖像是透明的url
// pen.globalCompositeOperation = "source-out"; // 只有目標圖像之外的源圖像顯示,其餘部分圖像是透明的spa
// pen.globalCompositeOperation = "destination-over"; // 默認值,能夠理解爲 源圖像 層級高於 目標圖像
// pen.globalCompositeOperation = "destination-atop"; // 源圖像之外的 目標圖像 是透明的
// pen.globalCompositeOperation = "destination-in"; // 只有源圖像之內的目標圖像顯示,其餘部分圖像是透明的
pen.globalCompositeOperation = "destination-out"; // 只有源圖像之外的目標圖像顯示,其餘部分圖像是透明的
// 源圖像(刮刮卡必須設置透明色,才能看見 myCanvas 的背景圖)
pen.beginPath();
pen.fillStyle = "blue";
pen.fillRect(300, 300, 100, 100);
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>刮刮卡案例</title> <style type="text/css"> body { width: 100%; color: #000; background: #96b377; font: 14px Helvetica, Arial, sans-serif; } #wrap { display: flex; flex-direction: column; justify-content: center; align-items: center; } </style> </head> <body> <div id="wrap"></div> <!-- javascript 代碼 --> <script type="text/javascript"> // 建立 畫布的width 畫布的height 背景顏色 父元素 function createCanvasTo(canvasWidth, canvasHeight, bgColor, parentObj){ var myCanvas = document.createElement("canvas"); myCanvas.width = canvasWidth; myCanvas.height = canvasHeight; myCanvas.innerText = " 您的瀏覽器不支持 canvas,建議更新或者更換瀏覽器。"; if(bgColor){ myCanvas.style.backgroundColor = bgColor; }; if(parentObj){ parentObj.appendChild(myCanvas); }; return myCanvas; }; /**** Start Coding ****/ var wrap = document.getElementById("wrap"); var myCanvas = createCanvasTo(400, 400, "#eee", wrap); myCanvas.style.backgroundImage = "url(./img/Loki.jpg)"; myCanvas.style.backgroundSize = "cover"; // 獲取畫筆 var pen = myCanvas.getContext("2d"); pen.fillStyle = '#a0a997'; // 填充的顏色 pen.strokeStyle = "blue"; // 筆的顏色 pen.lineWidth = 40; // 筆寬 pen.lineCap = "round"; // 圓形結束 pen.lineJoin = "round"; // 圓角 // 開始繪製 pen.beginPath(); pen.fillRect(0, 0, myCanvas.width, myCanvas.height); pen.globalCompositeOperation = "destination-out"; // 只有源圖像之外的目標圖像顯示,其餘部分圖像是透明的 myCanvas.onmousedown = function(e){ e = e || window.event; myCanvas.setCapture && myCanvas.setCapture(); var canvasX = myCanvas.getBoundingClientRect().left; var canvasY = myCanvas.getBoundingClientRect().top; pen.beginPath(); pen.moveTo(e.clientX-canvasX, e.clientY-canvasY); myCanvas.onmousemove = function(e){ e = e || window.event; pen.lineTo(e.clientX-canvasX, e.clientY-canvasY); pen.stroke(); }; myCanvas.onmouseup = function(){ myCanvas.onmousemove = null; myCanvas.onmouseup = null; myCanvas.clearCapture && myCanvas.clearCapture(); }; e.preventDefault && e.preventDefault(); return false; }; </script> </body> </html>