簡體   English   中英

基於 Canvas 中的字符串動態更改文本

[英]Dynamically Change text based on String in Canvas

我不確定這是否可行,而且我對 canvas 一般來說還很陌生,但我的目標是讀取一個字符串,如果該字符串包含一個特定的單詞,然后在離開 rest 的同時更改該特定單詞的特定顏色字符串正常。 因此,例如 text == degraded-performance 將文本更改為Purple ,但將文本的 rest 保持正常。 但是如果文本 == 降級性能和操作,將降級性能更改為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
您可以使用它在一行中“連接”不同顏色的文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM