裁切路徑和普通的canvas圖形差很少,不一樣的是它的做用是遮罩,用來隱藏路徑之外的部分。
clip() 將當前正在構建的路徑轉換爲當前的裁剪路徑,默認狀況下,canvas有一個與它自身同樣大的裁切路徑(也就是沒有裁切效果)html
<body> <canvas id="canvas" width="400" height="400" style="background:#f2f2f2"></canvas> <script> function draw() { var ctx = document.getElementById("canvas").getContext("2d"); ctx.fillRect(0, 0, 150, 150); ctx.translate(75, 75); //建立一個圓形的剪切路徑,對下面含有漸變色的背景進行剪切成圓形 ctx.beginPath(); ctx.arc(0, 0, 60, 0, Math.PI * 2, true); ctx.clip(); //draw background var lingrad = ctx.createLinearGradient(0, -75, 0, 75); lingrad.addColorStop(0, '#232256'); lingrad.addColorStop(1, '#143778'); ctx.fillStyle = lingrad; ctx.fillRect(-75, -75, 150, 150) //draw strars for (var j = 1; j < 50; j++) { ctx.save(); ctx.fillStyle = "#fff"; ctx.translate(75 - Math.floor(Math.random() * 150), 75 - Math.floor(Math.random() * 150)); drawStar(ctx, Math.floor(Math.random() * 4) + 2); ctx.restore(); } } function drawStar(ctx, r) { ctx.save(); ctx.beginPath(); ctx.moveTo(r, 0); for (var i = 0; i < 9; i++) { ctx.rotate(Math.PI / 5); if (i % 2 === 0) { ctx.lineTo(r / 0.525731 * 0.200811, 0) } else { ctx.lineTo(r, 0) } } ctx.closePath(); ctx.fill(); ctx.restore(); } draw() </script> </body>
解釋:先畫了一個黑色的背景,而後畫一個剪切路徑,接着畫顯示漸變色的矩形,最後畫一些隨機的星星,canvas
全部在剪切路徑上層的圖形都會隱藏剪切路徑以外的內容dom