HTML canvas clip() 方法
从画布中剪切 200*120 像素的矩形区域。然后,绘制一个红色矩形。只有被剪切区域内的红色矩形部分是可见的:
<span>没有进行clip():</span>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// 画一个矩形
ctx.rect(50, 20, 200, 120);
ctx.stroke();
// 画一个红色矩形
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 150, 100);
</script>
<span>有进行clip():</span>
<canvas id="myCanvas2" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。</canvas>
<script>
var c = document.getElementById("myCanvas2");
var ctx = c.getContext("2d");
//剪切一个矩形区域
ctx.rect(50, 20, 200, 120);
ctx.stroke();
ctx.clip();
//剪切之后画一个矩形
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 150, 100);
</script>
浏览器支持
![]()
![]()
![]()
![]()
![]()
Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 clip() 方法。
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
定义和用法
clip()方法从原始画布中剪切任意形状和尺寸。
提示:一旦剪切了某个区域,则所有之后的绘图都会被限制在被剪切的区域内(不能访问画布上的其他区域)。您也可以在使用 clip() 方法前通过使用 save() 方法对当前画布区域进行保存,并在以后的任意时间对其进行恢复(通过 restore() 方法)。
| JavaScript 语法: | context.clip(); |
|---|
HTML canvas 参考手册