画布的 .fillText 函数似乎在首次调用后停止工作

Canvas' .fillText function appears to stop working after first time called

本文关键字:调用 停止工作 fillText 函数      更新时间:2023-09-26

我只是在画布上绘画(画布菜鸟)。为了练习,我只是尝试创建一些中间有文本的透明圆形对象。创建文本的函数称为 writeName 。当我第一次创建对象的新实例时,它会写入我传递它的单词。问题是它不会在对象的第 2 个和第 3 个实例上写入文本。

在尝试查找任何错误时,我在writeName中插入了一个console.log,它告诉我每次都会调用该函数,并且参数确实正确传递给该函数,所以我无法弄清楚我做错了什么。我强烈怀疑这与fillText功能的工作方式有关。我做错了什么?为什么这行不通?

以下是该页面的完整代码:

<canvas id="myCanvas" width="1000" height="1000"></canvas>
<script>
    // Global Variables.
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.textAlign = 'center';
    ctx.textBaseline="middle";
    ctx.font = "20px Arial";
    // Function to generate the page icons.
    function pageObj(pgType, plot, lText) {
        writeName(plot[0], plot[1], lText);
        drwCirc(plot[0], plot[1]);
    }
    // Draws a circle for directories.
    function drwCirc(x, y){
        ctx.beginPath();
        ctx.arc(x, y, 60, 0, 2 * Math.PI, false);
        ctx.fillStyle = "rgba(0,0,0,0)"; // Transparent fill.
        ctx.fill();
        ctx.lineWidth = 6;
        ctx.strokeStyle = 'black';
        ctx.stroke();
    }
    // Writes the name of the file or directory in the circle.
    function writeName(x, y, text){
        console.log("X = " + x + "'n" + "Y = " + y + "'n" + "Text = " + text);
        ctx.fillText(text,x,y);
    }
    // The actual objects generated go here.
    var pageDemo = pageObj('dir', [500, 500], "index");
    var pageDemo1 = pageObj('dir', [250, 250], "page");
    var pageDemo2 = pageObj('dir', [0, 0], "tacos");

    //    ctx.beginPath();
    //    ctx.moveTo(centerX, centerY);
    //    ctx.lineTo(450, 50);
    //    ctx.stroke();
</script>

Blindman67给了我答案。他把它放在评论中,但不是对这个问题的回答。我在这里为可能遇到相同或类似问题的其他任何人提供答案:

您需要为文本设置填充样式。目前您使用默认值("黑色"),然后设置 fillStyle = "rgba(0,0,0,0)",因此下次调用 fillText 时,您将看不到任何内容。顺便说一句,这也将包括弧线。将 alpha 设置为 0 不会渲染任何内容。要渲染透明像素,您需要使用 ctx.clip 和 ctx.clearRect 或创建蒙版并使用 ctx.globalCompositeOperation 或使用 ctx.getImageData 和 ctx.setImageData 直接操作像素