当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


HTML canvas clearRect()用法及代码示例


clearRect()方法用于清除给定矩形内的指定像素。

用法:

context.clearRect( x, y, width, height )

参数:


  • x:它存储矩形左上角的x坐标。
  • y:它存储矩形左上角的y坐标。
  • width:它以像素为单位存储宽度。
  • height:它以像素为单位存储高度。

示例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML canvas clearRect() Method 
    </title> 
</head> 
  
<body> 
    <canvas id="GFG"
            width="500"
            height="300"> 
  </canvas> 
  
    <script> 
        var x = document.getElementById("GFG"); 
        var contex = x.getContext("2d"); 
        contex.fillRect(50, 50, 350, 200); 
        contex.clearRect(100, 100, 250, 100); 
        contex.stroke(); 
    </script> 
</body> 
  
</html>

输出:

示例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        HTML canvas clearRect() Method 
    </title> 
</head> 
  
<body> 
    <canvas id="GFG"
            width="500"
            height="300"> 
  </canvas> 
  
    <script> 
        var x = document.getElementById("GFG"); 
        var contex = x.getContext("2d"); 
        contex.fillStyle = "green"; 
        contex.fillRect(50, 50, 350, 200); 
        contex.clearRect(130, 60, 250, 100); 
        contex.stroke(); 
    </script> 
  
</body> 
  
</html>

输出:

支持的浏览器:

  • 谷歌浏览器
  • Internet Explorer 9.0
  • 火狐浏览器
  • 苹果浏览器
  • Opera


相关用法


注:本文由纯净天空筛选整理自R_Raj大神的英文原创作品 HTML | canvas clearRect() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。