画布的 .fillText 函数似乎在首次调用后停止工作
Canvas' .fillText function appears to stop working after first time called
我只是在画布上绘画(画布菜鸟)。为了练习,我只是尝试创建一些中间有文本的透明圆形对象。创建文本的函数称为 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 直接操作像素
相关文章:
- jQuery UI自动完成突然停止工作
- JavaScript打印功能使日历停止工作
- 下拉列表在使用z索引放置在前面后停止工作
- 由于响应中不存在“Access Control Allow Origin”标头,跨域请求停止工作
- 为什么ng控制器不调用或工作或功能不工作
- 注入工厂时,Angular停止工作
- React Native DeviceEventEmitter键盘WillShow停止工作
- Javascript作用域和Ajax调用;工作不正常
- JavaScript在更改css时停止工作
- Chrome地理定位在更新后停止工作
- 当控制台不在't在chrome中打开,有些项目不再可点击(有些js调用停止工作)
- 画布的 .fillText 函数似乎在首次调用后停止工作
- 添加参数时调用javascript函数停止工作,这真的不大声吗
- AJAX调用将元素添加到页面后,Bootstrap Scrollspy停止工作
- 将jQuery添加到HTA后,调用VBScript过程将停止工作
- jQuery ajax调用后,具有相同id的事件停止工作
- Javascript/Jquery在Ajax调用后停止工作
- jquery ui对话框已停止工作-出现错误“;无法调用方法'鼠标悬停'“未定义”;
- JavaScript在AJAX调用后停止工作
- JQuery拖拽和Javascript在ajax调用后停止工作