矩形一直出现在context.clearRect();之后;

A Rectangle keeps appearing after context.clearRect();

本文关键字:clearRect context 之后 一直      更新时间:2023-09-26

我的.rect()有问题。我已经使用.drawImage(canvas...)创建了一个网格,每当我使用.stroke()时,它就会再次出现。如何完全删除该矩形?

问候


工作jsFiddle


var canvas = document.getElementById('board');
var context = canvas.getContext('2d'),
    wt = canvas.width,
    ht = canvas.height;
canvas.onmousedown = function (e) {
    e.preventDefault(); // disabling selecting
    context.strokeStyle = "red";
    context.lineWidth = 1;
    context.rect(wt / 2 - 50, ht / 2 - 100, 100, 200);
    context.fillText("<- why is it here? didn't '"clearRect()'" delete it?", 8, 8);
    context.stroke();
};
function grid() {
    var h = 2.5,
        p = 2.5;
    context.rect(0.5, 0.5, 5, 5);
    context.strokeStyle = "#f0f0f0";
    context.stroke(); // creating a 5x5 small rectangle in top left corner
    for (i = 0; i < wt; i += p) {
        p *= 2;
        context.drawImage(canvas, p, 0); // replicating it horizontally...
    }
    for (i = 0; i < ht; i += h) {
        h *= 2;
        context.drawImage(canvas, 0, h); // ... and vertically
    }
    context.clearRect(0, 0, 5, 5); // here I am deleting that stroke, because I don't need it anymore
    context.drawImage(canvas, 0, 55, 5.5, 5.5, 0, 0, 5.5, 5.5); // drawing it with drawImage();
}
grid();

clearRect清除画布的一部分,而不是使用rect绘制的路径的一部分。调用beginPath()以清除在应用笔划时包含的前一个rect

请参阅此更新示例。