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>

本文内容由用户注册发布,仅代表作者或来源网站个人观点,不代表本网站的观点和立场,与本网站无关。本网系信息发布平台,仅提供信息存储空间服务,其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本网站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。如因作品内容侵权需删除与其他问题需要同本网联系的,请尽快通过本网的邮箱或电话联系。 
THE END
分享
二维码
< <上一篇
下一篇>>