javascript - 基于 Canvas 中的字符串动态更改文本
问题描述
我不确定这是否可行,而且我一般对画布还很陌生,但我的目标是读取一个字符串,如果该字符串包含一个特定的单词,然后将特定的单词更改为特定的颜色,同时保留其余部分字符串正常。例如,文本 == 降级性能将文本更改为Purple
,但保留文本的其余部分正常。但是如果文本 == 降级性能和可操作性,请将降级性能更改为Purple
,并将操作性更改为Green
// == Color Rules ==
// Partial Outage = Orange
// Major Outage = Red
// Degraded Performance = Purple
// Under Maintenance = Grey
// Operational = Green
function degraded() {
ctx.fillStyle = "Purple";
ctx.fill();
ctx.fillText("Partial Outage", 75, 50);
}
function operational() {
ctx.fillStyle = "Green";
ctx.fill();
ctx.fillText("Operational", 75, 50);
}
// JSON
result = {"PF":"operational","PU":"degraded-performance","EA":"operational"}
const json = JSON.stringify(result, null, 1);
const removeBracket = json.replace(/{/g, '').replace(/}/g, '');
const unquoted = removeBracket.replace(/\"/g, "");
// load bg
ctx = canvas.getContext("2d");
img = document.getElementById("bg");
ctx.drawImage(img, 0, 0);
// Add to String and Split Lines
var x = 10;
var y = 50;
var lineheight = 30;
splitlines = ("PF" + ' ' + result.PF.replace(new RegExp(' ', 'g'), '\n') +
"\n" + "PU" + ' ' + result.PU + "\n" + "EA" + ' ' + result.EA)
// Split Lines
var lines = splitlines.split('\n');
for (var i = 0; i<lines.length; i++){
ctx.fillText(lines[i], x, y + (i*lineheight) );
}
// If string contains a text swap out THAT specific text. How can i do that?
if (lines.includes('Operational') == true) {
operational();
} else {
}
解决方案
这是我要做的:
您需要循环内的 if 语句设置正确的颜色
json = {
"PF": "operational",
"PU": "degraded-performance",
"EA": "partial-outage"
}
canvas = document.getElementById("c")
ctx = canvas.getContext("2d");
var x = 10;
var y = 10;
for (var prop in json) {
if (json[prop].includes("degraded-performance")) {
ctx.fillStyle = "Purple";
} else if (json[prop].includes("partial-outage")) {
ctx.fillStyle = "Orange";
} else {
ctx.fillStyle = "Green";
}
ctx.fillText(prop + ' ' + json[prop], x, y);
y += 20
}
<canvas id="c"></canvas>
如果您的文本将在一行中查看 measureText https://www.w3schools.com/tags/canvas_measuretext.asp
您可以使用它在一行中“连接”不同颜色的文本。
推荐阅读
- python - 有效地遍历数据框以识别超过 2000 万个不同标题中的标签
- python - 旋转时禁用图形中的“阴影”
- excel - Excel中的交叉连接
- flutter - 如何在具有嵌套小部件的列上实现 SingleChildScrollView?
- javascript - 如何根据MongoDB中的key直接从嵌套文档中获取文档
- excel - 用于 LastRow 计算的 VBA 宏 Microsoft Excel 中的应用程序定义或对象定义错误
- bash - 从 iCloud 文件夹运行可执行脚本
- c# - 使用正则表达式从自由文本中提取键值
- ansible - 如何按顺序安装ansible yum包
- docker - 在远程连接中使用 rviz “无法连接到任何 X 显示器。”