首页 > 解决方案 > 基于 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 {

            }

标签: javascriptarrayscanvashtml5-canvas

解决方案


这是我要做的:

您需要循环内的 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
您可以使用它在一行中“连接”不同颜色的文本。


推荐阅读