我不知道这是否可能,而且我对画布也很陌生,但我的目标是读取一个字符串,如果该字符串包含一个特定的单词,那么改变该特定单词的特定颜色,同时保持字符串的其余部分正常。 因此,例如是text == degraded-performance将该文本改为 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>
如果你的文本将是一行,请看测量文本。 https:/www.w3schools.comtagscanvas_measuretext.asp 你可以用它在一行中 "连缀 "不同颜色的文字。