我刚开始在画布上画画(Canvas Noob)。为了练习,我只是想在中间创建一些带有文本的透明圆形对象。创建文本的函数称为writeName
。我第一次创建对象的新实例时,它会写出我传递它的单词。 问题是它不会在对象的第2个和第3个实例上写入文本。
在尝试查找任何错误时,我在console.log
中插入writeName
,告诉我每次都调用该函数,并且参数确实正确地传递给函数,所以我可以'弄清楚我做错了什么。我强烈怀疑它与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>
答案 0 :(得分:0)
Blindman67给了我答案。他发表评论,但不作为对此问题的答案。我在这里为可能遇到相同或相似问题的其他人提供答案:
您需要为文本设置fillStyle。当前,您使用默认值(“黑色”),然后设置fillStyle =“ rgba(0,0,0,0)”,因此,下次调用fillText时,您将看不到任何内容。顺便说一句,其中还将包括弧。将alpha设置为0将不会呈现任何内容。要渲染透明像素,您将需要使用ctx.clip和ctx.clearRect或创建蒙版,并使用ctx.globalCompositeOperation或直接使用ctx.getImageData和ctx.setImageData
操作像素