In the real world, we use brushes to draw on the drawing board; in html5 canvas, we can also use the canvas's brush - the CanvasRenderingContext2D object to draw on the canvas. As we all know, our brushes are generally used with erasers to correct mistakes during the painting process and repaint. In html5 canvas, the CanvasRenderingContext2D object also provides us with an eraser that can be reused forever - the clearRect() method.
XML/HTML CodeCopy content to clipboard
-
clearRect(x, y, width, height)
The clearRect() method of the CanvasRenderingContext2D object is used to clear all graphic pixels in the rectangular area of the canvas with the specified coordinate point (x, y) as the upper left corner, width as width, and height as height.
Now, let’s look at a practical example. We first draw a solid circle with a radius of 50px, and then use the eraser clearRect() to erase a local area within it. The original html5 code for drawing a circle is as follows:
JavaScript CodeCopy content to clipboard
-
-
-
-
"UTF-8">
-
Getting started example of using HTML5 clearRect() to erase a specified rectangular area
-
-
-
-
-
-
Your browser does not support the canvas tag.
-
-
-
-
-
The corresponding display effect is as follows:
Now, we use the clearRect() method to erase the rectangular area of the solid circle with the center (100,100) as the center and 10px on each side.
JavaScript CodeCopy content to clipboard
The corresponding display effect is as follows (is it a bit like a copper coin?).
On the page, we can erase an area on the page to display the background image.
In the example below we erase the white space in the rectangle and let it show the page background:
JavaScript CodeCopy content to clipboard
-
-
"zh">
-
-
"UTF-8">
-
clearRect()
-
-
-
-
"canvas-warp">
-
-
你的浏览器居然不支持Canvas?!赶快换一个吧!!
-
-
-
-
<script> </span> </li>
<li class="alt">
<span> window.onload = </span><span class="keyword">function</span><span>(){ </span> </li>
<li>
<span> </span><span class="keyword">var</span><span> canvas = document.getElementById(</span><span class="string">"canvas"</span><span>); </span> </li>
<li class="alt">
<span> canvas.width = 800; </span> </li>
<li>
<span> canvas.height = 600; </span> </li>
<li class="alt">
<span> </span><span class="keyword">var</span><span> context = canvas.getContext(</span><span class="string">"2d"</span><span>); </span> </li>
<li>
<span> context.fillStyle = </span><span class="string">"#FFF"</span><span>; </span> </li>
<li class="alt">
<span> context.fillRect(0,0,800,600); </span> </li>
<li>
<span> </span> </li>
<li class="alt">
<span> </span><span class="comment">//清空画布 </span><span> </span> </li>
<li>
<span> context.clearRect(0,0,canvas.width,canvas.height); </span> </li>
<li class="alt">
<span> </span> </li>
<li>
<span> }; </span> </li>
<li class="alt">
<span></script>
-
-