ZetCode

JavaScript Canvas clearRect 教程

最后修改于 2025 年 4 月 3 日

在本文中,我们将探讨 JavaScript 中的 Canvas clearRect 方法。此方法对于清除 HTML canvas 的特定矩形区域至关重要。掌握 clearRect 对于动画和动态图形至关重要。

基本定义

clearRect 方法将指定矩形区域内的像素清除为透明黑色(rgba(0,0,0,0))。它通常用于擦除 canvas 的一部分或为新绘图准备区域。

该方法接受四个参数:左上角的 x 和 y 坐标,以及矩形的宽度和高度。它仅影响指定区域,而不会改变其他 canvas 内容。

clearRect 的基本用法

此示例演示了如何从已填充的 canvas 中清除一个矩形区域。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic clearRect</title>
</head>
<body>

<canvas id="myCanvas" width="300" height="200"></canvas>

<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    
    // Fill entire canvas with blue
    ctx.fillStyle = 'blue';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Clear a rectangle in the middle
    ctx.clearRect(100, 50, 100, 100);
</script>

</body>
</html>

在这个基本示例中,我们首先使用 fillRect 将整个 canvas 填充为蓝色。然后我们使用 clearRect 在中间创建一个透明矩形。

clearRect 参数 (100,50,100,100) 意味着:从 x=100,y=50 开始,清除一个宽度为 100 像素、高度为 100 像素的区域。这展示了最简单的 clearRect 用法。

局部 Canvas 清除

此示例展示了如何在保留其他内容的同时清除多个区域。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Partial Clearing</title>
</head>
<body>

<canvas id="myCanvas" width="400" height="300"></canvas>

<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    
    // Draw a complex pattern
    ctx.fillStyle = 'green';
    for (let i = 0; i < canvas.width; i += 20) {
        for (let j = 0; j < canvas.height; j += 20) {
            ctx.fillRect(i, j, 10, 10);
        }
    }
    
    // Clear specific areas
    ctx.clearRect(50, 50, 100, 50);
    ctx.clearRect(250, 100, 100, 100);
    ctx.clearRect(150, 200, 200, 50);
</script>

</body>
</html>

在这里,我们首先通过在 canvas 上绘制小的绿色正方形来创建网格图案。然后我们清除不同位置的三个矩形区域。

每次调用 clearRect 都会从其指定区域中删除内容,从而在图案中创建“孔”。这演示了选择性清除并保留其他 canvas 内容。

使用 clearRect 进行动画

此示例展示了 clearRect 如何通过清除帧来实现平滑动画。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Animation with clearRect</title>
</head>
<body>

<canvas id="myCanvas" width="400" height="200"></canvas>

<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    
    let x = 0;
    const ballRadius = 20;
    
    function animate() {
        // Clear only the area needed for animation
        ctx.clearRect(x - ballRadius - 1, 0, 
                     ballRadius * 2 + 2, canvas.height);
        
        // Draw new ball position
        ctx.beginPath();
        ctx.arc(x, 100, ballRadius, 0, Math.PI * 2);
        ctx.fillStyle = 'red';
        ctx.fill();
        
        x += 2;
        if (x > canvas.width + ballRadius) x = -ballRadius;
        
        requestAnimationFrame(animate);
    }
    
    animate();
</script>

</body>
</html>

此动画在 canvas 上移动一个红球。我们没有在每一帧都清除整个 canvas,而是只清除球的最后位置周围的区域。

clearRect 参数考虑了球的半径加上 1 像素的填充。这种优化的清除方式减少了闪烁,并与完全清除 canvas 相比提高了性能。

交互式清除

此示例演示了通过鼠标移动进行交互式清除。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Interactive Clearing</title>
</head>
<body>

<canvas id="myCanvas" width="500" height="400"></canvas>

<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    
    // Fill canvas with gradient
    const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
    gradient.addColorStop(0, 'purple');
    gradient.addColorStop(1, 'orange');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Clear on mouse move
    canvas.addEventListener('mousemove', (e) => {
        const rect = canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        ctx.clearRect(x - 25, y - 25, 50, 50);
    });
</script>

</body>
</html>

这会创建一个带有垂直渐变的 canvas。当鼠标移动时,它会在光标位置中心清除 50x50 像素的正方形,从而显示透明度。

mousemove 事件计算相对于 canvas 的坐标。然后 clearRect 创建一个跟随鼠标的清除效果,展示了交互式用法。

高级:使用复合操作进行清除

此示例将 clearRect 与 globalCompositeOperation 结合使用以实现效果。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Composite Clearing</title>
</head>
<body>

<canvas id="myCanvas" width="500" height="400"></canvas>

<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    
    // Draw background image (simulated)
    ctx.fillStyle = 'lightblue';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'brown';
    for (let i = 0; i < 100; i++) {
        ctx.fillRect(
            Math.random() * canvas.width,
            Math.random() * canvas.height,
            5, 5
        );
    }
    
    // Set composite mode
    ctx.globalCompositeOperation = 'destination-out';
    
    // Clear with shapes instead of rectangles
    function clearCircle(x, y, r) {
        ctx.beginPath();
        ctx.arc(x, y, r, 0, Math.PI * 2);
        ctx.fill();
    }
    
    // Interactive clearing
    canvas.addEventListener('mousemove', (e) => {
        const rect = canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        clearCircle(x, y, 30);
    });
</script>

</body>
</html>

这个高级示例使用 globalCompositeOperation 来创建非矩形清除效果。我们将模式设置为 'destination-out',这使得任何新绘图都会清除现有内容。

我们不使用 clearRect,而是使用 fill 和 arc 来创建圆形清除区域。鼠标移动会以圆形而不是矩形清除内容,展示了创意的清除技术。

来源

MDN Canvas clearRect 文档

在本文中,我们探索了使用 clearRect 管理 canvas 内容的各种技术。从基本清除到高级动画和效果,clearRect 是 canvas 操作的强大工具。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 JS Canvas 教程