小码哥的IT人生

HTML canvas clearRect() 方法 详解

HTML基础 2022-06-02 15:26:09小码哥的IT人生shichen

HTML canvas clearRect() 方法

定义和用法

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

实例

在给定矩形内清空一个矩形:

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(0,0,300,150);
ctx.clearRect(20,20,100,50);

 

完整实例【亲自试一试】:

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(0,0,300,150);
ctx.clearRect(20,20,100,50);
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

语法

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

参数值

参数 描述
x 要清除的矩形左上角的 x 坐标
y 要清除的矩形左上角的 y 坐标
width 要清除的矩形的宽度,以像素计
height 要清除的矩形的高度,以像素计

浏览器支持

表中的数字注明了首个完全支持该属性的浏览器版本。

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

注释:Internet Explorer 8 以及更早的版本不支持 <canvas> 元素。

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024