HTML5 Canvas Clipping Region属性定义剪裁区域
gooood个人博客网站
canvas
要使用HTML5画布定义剪裁区域,我们可以绘制路径,然后使用画布上下文的clip()方法。 之后绘制的所有内容都将被绑定在剪切区域内。 一旦我们完成了在裁剪区域内绘制内容,我们可以使用restore()方法将画布上下文返回到其原始状态,以便不将其他绘图绑定到裁剪区域。
在本教程中,我们将通过绘制圆形然后使用clip()来定义圆形剪切区域,然后我们将绘制一些在圆形路径内剪切的圆形。 接下来,我们将使用restore()方法将画布上下文恢复为其原始状态,然后在原始剪切区域周围绘制一个环。
html代码:
<!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var x = canvas.width / 2; var y = canvas.height / 2; var radius = 75; var offset = 50; /* * save() allows us to save the canvas context before * defining the clipping region so that we can return * to the default state later on */ context.save(); context.beginPath(); context.arc(x, y, radius, 0, 2 * Math.PI, false); context.clip(); // draw blue circle inside clipping region context.beginPath(); context.arc(x - offset, y - offset, radius, 0, 2 * Math.PI, false); context.fillStyle = 'blue'; context.fill(); // draw yellow circle inside clipping region context.beginPath(); context.arc(x + offset, y, radius, 0, 2 * Math.PI, false); context.fillStyle = 'yellow'; context.fill(); // draw red circle inside clipping region context.beginPath(); context.arc(x, y + offset, radius, 0, 2 * Math.PI, false); context.fillStyle = 'red'; context.fill(); /* * restore() restores the canvas context to its original state * before we defined the clipping region */ context.restore(); context.beginPath(); context.arc(x, y, radius, 0, 2 * Math.PI, false); context.lineWidth = 10; context.strokeStyle = 'blue'; context.stroke(); </script> </body> </html>