Холст хрустящий рендеринг текста - PullRequest
0 голосов
/ 17 апреля 2020

Я использую электрон (nodejs Framework), и я хочу сделать хрустящий текст для преобразования его в растровое изображение и показать его на светодиодном кирпиче. как программное обеспечение для светодиодных шоу, пожалуйста, помогите.

мой код работает, но он зависит от системы, он отлично работает на некоторых компьютерах, но на некоторых компьютерах размыт.

вызывает параметр main. js.

let height = 96;
let width = 288;
let letterSpacing = 1;
var font = "Arial";
var fontSize = 11;
let text_x = 1;
let text_y = 1;
const canvas = new Canvas(height, width, letterSpacing, font, fontSize, text_x, text_y);

вот мой холст. js файл.

class Canvas {
constructor(height, width, latterSpacing = 1, font, fontSize, text_x, text_y) {
    this.width = width;
    this.height = height;
    this.letterSpacing = latterSpacing;
    this.font = font;
    this.fontSize = fontSize;
    this.text_x = text_x;
    this.text_y = text_y;

    this.maxWidth = 32;
    this.offset = 0.5;

    this.canvas = document.getElementById("myCanvas");
    this.ctx = this.canvas.getContext("2d");
}

PIXEL_RATIO = (function () {
    // var ctx = document.createElement("canvas").getContext("2d"),
    var ctx = document.getElementById("myCanvas").getContext("2d"),
        // var ctx = this.ctx,
        dpr = window.devicePixelRatio || 1,
        bsr = ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio || 1;

    return dpr / bsr;
})();

setwidth(maxwidth) {
    this.maxWidth = maxwidth;
    // this.offset = ofset;
}

setoffset(ofset) {
    // this.maxWidth = maxwidth;
    this.offset = ofset;
}

createHiDPICanvas = function (w, h, ratio) {
    if (!ratio) { ratio = this.PIXEL_RATIO; }
    // var can = document.createElement("canvas");
    var can = this.canvas;
    can.width = w * ratio;
    can.height = h * ratio;
    can.style.width = w + "px";
    can.style.height = h + "px";
    can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
    return can;
}

createCanvas() {
    try {
        const canvas = document.getElementById("myCanvas");
        this.canvas.retinaResolutionEnabled = false;
        // this.canvas.style.letterSpacing = "1px";
        this.canvas.height = this.height;
        this.canvas.width = this.width;

        this.canvas.style.letterSpacing = `${this.letterSpacing}px`                                    
        /*word spacing*/

        // var can = this.createHiDPICanvas(this.width, this.height, 4)
        // this.ctx = can.getContext("2d")

        this.ctx.beginPath();
        // this.ctx = this.canvas.getContext("2d");
        this.ctx.fillStyle = "#FF0000";
        this.ctx.font = `${this.fontSize}px ` + this.font;                                            
        /*Font style and size*/
        this.ctx.strokeStyle = "#FF0000";
        this.ctx.textBaseline = "top";
        this.ctx.textAlign = 'start';
        this.ctx.shadowOffsetX = 0;

        this.canvas.retinaResolutionEnabled = false;

        // this.ctx.fillText("WELCOME TO TICO", 10, 20);
        return true;
    } catch (error) {
        return false;
    }
}

clrCanvas(ix = 0, iy = 0, ex = this.canvas.width, ey = this.canvas.height) {
    this.ctx.clearRect(ix, iy, ex, ey);
}

fillTextCanvas(str, row = 0, col = 0, vac = 0, hac = 1, _fontSize = this.fontSize, _font = this.font) 
{

    this.ctx.font = `${_fontSize}px ` + _font;

    if (vac) {
        col = ((this.canvas.height - (str.length * _fontSize)) / 2) + 1;
    }

    if (hac) {
        this.ctx.textAlign = "center";
        row = this.width / 2;
    }

    for (let index = 0; index < str.length; index++) {
        // const element = array[index];
        let y = (_fontSize * index) + col;
        // this.ctx.fillText(str[index], width / 2, y);                                             
        /*text,x,y*/
        this.ctx.fillText(str[index], row - 0.8, y - 0.8);                                             
         /*text,x,y*/
        // this.ctx.fillText("hello", width/2, y);                                             
        /*text,x,y*/
    }

    // display_hex["Screen2"] = jsonArr;
    // fillMatrix(jsonArr);
}

async getBitmap() {
    var jsonArr = {};
    var bin = '';
    for (var j = 0; j < this.canvas.width; j++) {
        bin = ""
        for (var i = 0; i <= this.canvas.height; i++) {
            var data = this.ctx.getImageData(j, i, 1, 1);                         /*getPixel,x,y*/

            if (!(i % 32) && i) {
                // jsonArr[j + (width * (Math.floor(i / 32) - 1))] = ("0x" + (("00000000" + 
             ConvertBase.bin2hex(bin)).substr(-8)));
                jsonArr[j + (this.width * (Math.floor(i / 32) - 1))] = 
                parseInt(ConvertBase.bin2dec(bin));
                bin = "";
            }

            if (data['data'][0] >= 200 && data['data'][3] >= 90) {
                bin += "1";
            } else {
                bin += "0";
            }
        }
    }

    return jsonArr;
}

fillCanvas(_char, row, col, _fontSize = 11, _font = "Arial") {
    this.clrCanvas();
    this.ctx.font = `${_fontSize}px ` + _font;
    this.ctx.textAlign = "start";
    this.ctx.imageSmoothingEnabled = false;

    // let linesPos = [[0, 45, 80, 119, 157, 196, 235], [1, 24, 36, 48, 60, 72, 84]]
    // let linesPos = [[0, 49, 81, 119, 157, 196, 235], [1, 22, 33, 44, 55, 66, 77]]
    let linesPos = [[0, 60, 98, 135, 174, 213, 252], [1, 23, 34, 45, 56, 67, 78]]

    this.findColPos(_char);

    // console.log(_char)

    for (let _row = row; _row < _char.length; _row++) {
        // let y = parseInt(text_y) + ((parseInt(fontSize) + 2) * _row);
        let y = parseInt(this.text_y + 1) + ((parseInt(_fontSize)) * _row);

        for (let index = col; index < _char[_row].length; index++) {
            let x = parseInt(this.text_x) + linesPos[0][index];

            console.log(this.ctx.measureText(_char[_row][index]).width)
            // this.ctx.fillText(_char[_row][index], x + 1.8, y + 0.8,32);                                             
            /*text,x,y*/
            this.ctx.fillText(_char[_row][index], x + this.offset, y + this.offset, this.maxWidth);                                             
            /*text,x,y*/

            this.ctx.moveTo(0, linesPos[1][index + 1] + 0.5);
            this.ctx.lineTo(this.canvas.width, linesPos[1][index + 1] + 0.5);

            this.ctx.moveTo(linesPos[0][index] + 0.5, 0);
            this.ctx.lineTo(linesPos[0][index] + 0.5, this.canvas.height);
        }
    }

    this.ctx.stroke();
    this.ctx.strokeRect(0, 0, this.canvas.width, this.canvas.height);

    // display_hex["Screen1"] = jsonArr;

    // canvasImg["Screen1"] = ($('#myCanvas')[0]).toDataURL("image/png");
    // fillMatrix(jsonArr);
    // return jsonArr;
}

findColPos(__char) {
    let maxRow = []
    maxRow[0] = 0;
    let splitData = [];

    maxRow[0] = [];
    maxRow[1] = [];
    for (let pos = 0; pos < __char[0].length; pos++) {
        if (__char[0][pos].split(" ")[1]) {
            splitData.push(__char[0][pos].split(" ")[1]);
        } else {
            // __char[0][pos] = "";
            splitData[pos] = " "
        }
        __char[0][pos] = __char[0][pos].trim().split(" ")[0]; //_char[0][pos] _char[0].splice[];
        // _char[0][pos] = splitData[0];
        // _char[0].splice
        // console.log(_char[0][pos].split(" ")[0]); //_char[0][pos] _char[0].splice[];
    }
    console.log(__char)
    __char.splice(1, 0, splitData)
    console.log(__char)

    for (let row = 0; row < __char.length; row++) {
        for (let col = 0; col < __char[row].length; col++) {
            let width = this.ctx.measureText(__char[row][col]).width + 3;
            if (!maxRow[0][col + 1]) {
                maxRow[0][col + 1] = 0;
            }
            maxRow[0][col + 1] = maxRow[0][col + 1] < width ? width : maxRow[0][col + 1];
        }
    }
    // console.log(maxRow)

    for (let i = 1; i < maxRow.length; i++) {
        maxRow[0][i] = maxRow[0][i] + maxRow[0][i - 1];

    }


    /* for (let index = 0; index < _char.length; index++) {
        // const element = array[index];
        maxRow[index] = ctx.measureText(_char[index]).width;
    } */
    // _char = __char
    return maxRow;
}

createFonts(start, end) {
    let arr = [];
    // clearEvents();
    for (let index = "/".charCodeAt(0); index <= ":".charCodeAt(0); index++) {
        // const element = array[index];
        // fillCanvas(index);
        let txt = String.fromCharCode(index);
        fillTextCanvas(txt, 0, 0, 1, 0, 32);
        createCanvas(32, this.ctx.measureText(txt).width, 32);
        this.ctx.textBaseline = "middle";
        // fillTextCanvas(txt, text_x, text_y);
        this.clrCanvas();
        fillTextCanvas(txt, 0, 0, 1, 0, 32);
        arr.push(display_hex);
        // fillMatrix();
    }
    console.log(JSON.stringify(arr));
    // startEvents();
}

findFirstPositive(b, a, i, c) {
    c = (d, e) => e >= d ? (a = d + (e - d) / 2, 0 < b(a) && (a == d || 0 >= b(a - 1)) ? a : 0 >= 
   b(a) ? c(a + 1, e) : c(d, a - 1)) : -1
    for (i = 1; 0 >= b(i);) i *= 2
    return c(i / 2, i) | 0
}

getDPI() {
    var dpi = findFirstPositive(x => matchMedia(`(max-resolution: ${x}dpi)`).matches);
    return dpi
}

getImage() {
        return this.canvas.toDataURL('image/png', 1.0);
    }
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = Canvas;
}

1 Ответ

0 голосов
/ 17 апреля 2020

Канва не учитывает соотношение пикселей вашего устройства, это , а не специфическая c проблема с электронами.

Код, который вы скопировали и вставили из другого StackOverflow, не будет работать, потому что вы снова измените размер / высоту без соблюдения соотношения. Если вы раскомментируете его и правильно настроите, он будет работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...