All fontFamily not vertically in middle of <span> in HTML

57 Views Asked by At

I am generating HTML from Fabric JS JSON.

But certain font families are not rendering in the middle of <span> elements.

Font Not rendering as Expected : Choko Pain , Nurjan, Eczar Extra Bold, VarianeScript

As I shown in Below Roboto font render at Middle of Span in HTML but chokoPlain font render at bottom of span.

I want all FontFamily to render in the middle of the span, just like in FabricJS canvas.

<html id="#html">

<head>
    <meta charset="UTF-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>




    <style type="text/css">
        body,
        p,
        div {
            font-weight: 100 !important;
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            width: 100%;
        }

        #chart-Container,
        .canvas-container,
        .hidden-div,
        #cropCanvas,
        #curveCanvas {
            display: none;
        }

        #div {
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
            font-weight: normal;
            overflow: hidden;
            position: relative !important;
        }

        .clip-text {
            -webkit-background-clip: text !important;
        }
    </style>
</head>

<body>

    <div id="div">
        <span id="chart-Container"></span>
    </div>

    <canvas id="curveCanvas"></canvas>
    <canvas id="cropCanvas"></canvas>
    <div class="hidden-div"></div>
    <script>

        var json = {
            "background_json": {
                "background_image": "",
                "background_color": "#ffde59"
            },
            "sample_image": "",
            "height": 800,
            "width": 650,
            "display_height": 800,
            "display_width": 650,
            "display_size_type": "px",
            "user_template_category": "Flyer",
            "is_featured": 0,
            "is_portrait": 0,
            "page_id": 614458,
            "page_index": 1,
            "canvasJSON": {
                "objects": [
                    {
                        "type": "i-text",
                        "originX": "left",
                        "originY": "top",
                        "left": 15,
                        "top": 289,
                        "width": 310,
                        "height": 38,
                        "fill": "#ffffff",
                        "stroke": "#ffffff",
                        "strokeWidth": 0,
                        "strokeDashArray": null,
                        "strokeLineCap": "butt",
                        "strokeLineJoin": "miter",
                        "strokeMiterLimit": 10,
                        "scaleX": 1,
                        "scaleY": 1,
                        "angle": 0,
                        "flipX": false,
                        "flipY": false,
                        "opacity": 1,
                        "shadow": {
                            "color": "#000000",
                            "blur": 0,
                            "offsetX": 0,
                            "offsetY": 0,
                            "affectStroke": false
                        },
                        "visible": true,
                        "clipTo": null,
                        "backgroundColor": "",
                        "fillRule": "nonzero",
                        "globalCompositeOperation": "source-over",
                        "transformMatrix": null,
                        "skewX": 0,
                        "skewY": 0,
                        "text": "ADD HEADING TEXT",
                        "fontSize": 34,
                        "fontWeight": "bold",
                        "fontFamily": "Roboto-Regular",
                        "fontStyle": "",
                        "lineHeight": 1.16,
                        "textDecoration": "",
                        "textAlign": "left",
                        "textBackgroundColor": "#16cee7",
                        "charSpacing": 0,
                        "customSourceType": "text_json",
                        "id": 472947,
                        "bg_image": "",
                        "texture_image": "",
                        "excludeFromExport": false,
                        "_controlsVisibility": {
                            "tl": true,
                            "tr": true,
                            "br": true,
                            "bl": true,
                            "ml": false,
                            "mt": false,
                            "mr": false,
                            "mb": false,
                            "mtr": true
                        },
                        "isLocked": false,
                        "styles": {}
                    },
                    {
                        "type": "i-text",
                        "originX": "left",
                        "originY": "top",
                        "left": 354,
                        "top": 289,
                        "width": 285,
                        "height": 38,
                        "fill": "#ffffff",
                        "stroke": "#ffffff",
                        "strokeWidth": 0,
                        "strokeDashArray": null,
                        "strokeLineCap": "butt",
                        "strokeLineJoin": "miter",
                        "strokeMiterLimit": 10,
                        "scaleX": 1,
                        "scaleY": 1,
                        "angle": 0,
                        "flipX": false,
                        "flipY": false,
                        "opacity": 1,
                        "shadow": {
                            "color": "#000000",
                            "blur": 0,
                            "offsetX": 0,
                            "offsetY": 0,
                            "affectStroke": false
                        },
                        "visible": true,
                        "clipTo": null,
                        "backgroundColor": "",
                        "fillRule": "nonzero",
                        "globalCompositeOperation": "source-over",
                        "transformMatrix": null,
                        "skewX": 0,
                        "skewY": 0,
                        "text": "ADD HEADING TEXT",
                        "fontSize": 34,
                        "fontWeight": "bold",
                        "fontFamily": "ChokoPlain",
                        "fontStyle": "",
                        "lineHeight": 1.16,
                        "textDecoration": "",
                        "textAlign": "left",
                        "textBackgroundColor": "#14e8f8",
                        "charSpacing": 0,
                        "customSourceType": "text_json",
                        "id": 546246,
                        "bg_image": "",
                        "texture_image": "",
                        "font_path": "fonts/choko_plain.otf",
                        "excludeFromExport": false,
                        "_controlsVisibility": {
                            "tl": true,
                            "tr": true,
                            "br": true,
                            "bl": true,
                            "ml": false,
                            "mt": false,
                            "mr": false,
                            "mb": false,
                            "mtr": true
                        },
                        "isLocked": false,
                        "styles": {}
                    }
                ],
                "background": "#ffde59"
            }

        };
        var curveTextJson;

        $(function () {
            var elements = [];
            var div_el = document.getElementsByTagName("div")[0];
            div_el.style.height = json.height;
            div_el.style.width = json.width;
            document.body.style.fontFamily = "aAidilfitri";
            if (json.background_json && json.background_json.background_color != "") {
                div_el.style.backgroundColor = json.background_json.background_color;
            }
            div_el.style.position = "absolute";


            // For iText json data
            if (json.canvasJSON && json.canvasJSON.objects.length > 0) {
                var font_array = [];
                json.canvasJSON.objects.forEach((text, index) => {
                    if (text.type == "i-text") {
                        let { left, top, height, width } = text;
                        let isfontFamily = false;
                        let totalTopChoko;
                        let total_height;

                        if (left > json.width) {
                            total_height = (left - json.width) * 2;
                        }
                        else if (top > json.height) {
                            total_height = ((top - json.height) * 2) + 2;
                        }



                        let iText = document.createElement("p");
                        iText.style.left = `${(left > json.width) ? json.width : left}px`; //`${left || 0}`
                        iText.style.top = `${top > json.height ? json.height : top}px`;  //`${top || 0}px`; 
                        iText.style.height = `${(left > json.width) || (top > json.height) ? height - total_height : height}px`;
                        iText.style.width = width;
                        iText.style.whiteSpace = 'nowrap';
                        iText.style.opacity = text.opacity;
                        iText.style.position = "absolute";
                        iText.style.display = "flex";
                        iText.style.userSelect = "none";



                        // Load Font
                        if (!font_array.includes(text.fontFamily)) {
                            font_array.push(text.fontFamily);


                            let path = "";
                            if (text.font_path && text.font_path != '') {
                                path = text.font_path.replaceAll(' ', '%20');
                            }

                            let font_path = text.font_path ? 'https://db.onlinewebfonts.com/t/6c2c79efb5287200bdd8ca03a187db5d.ttf' : 'https://db.onlinewebfonts.com/t/03613b6e684c3d8421fc15ef7e0214b5.ttf';

                            new FontFace(text.fontFamily, `url(${font_path})`)
                                .load()
                                .then(function (loadedFace) {
                                    document.fonts.add(loadedFace);
                                })
                                .catch(function (error) {
                                    console.log(error, "error");
                                });
                        }

                        let isMultiLine = text.text.includes("\n");
                        let hasOverline = text.textDecoration.includes("overline");
                        let hasShadow =
                            text.shadow.offsetX !== 0 || text.shadow.offsetY !== 0 || text.shadow.blur !== 0;
                        let hasBGColor = text.textBackgroundColor && text.textBackgroundColor !== "";
                        let isPattern = text.fill.type === "pattern";
                        let isGradiant = text.fill.type === "linear" || text.fill.type === "radial";
                        let hasStrokeWidth = text.strokeWidth > 0;

                        // General

                        let style;

                        let iTextHolder = document.createElement("span");
                        // Inital Styling
                        let otherText = text.text;
                        let regex = /</g;
                        let matches = otherText.match(regex);

                        if (matches !== null) {
                            let convertedText = otherText.replace(regex, '&lt;');
                            iTextHolder.innerHTML = convertedText;
                        }
                        else {
                            iTextHolder.innerText = otherText;
                        }


                        style = `
                                        display: flex;
                                        align-items: center;
                                        height: ${(left > json.width) || (top > json.height) ? height - total_height : height}px;
                                        font-family: ${text.fontFamily};
                                        font-size: ${Math.round(text.fontSize)}px;
                                        ${text.fontStyle !== "" ? `font-style: ${text.fontStyle};` : ""}
                                        ${text.fontWeight !== ""
                                ? `font-weight: ${text.fontWeight};`
                                : ""
                            }
                                        ${!isGradiant && !isPattern && text.fill !== ""
                                ? `color: ${text.fill};`
                                : ""
                            }   
                                        
                                        line-height: ${text.lineHeight};
                                        transform: rotate(${text.angle}deg);
                                        transform-origin: top left;
                                        letter-spacing: ${text.charSpacing / 1000}em;
                                        margin: 0;
                                        margin-top: 0px !important;
                                        padding-right: ${(Math.round(text.fontSize) * 10) / 60}px;
                                    `;




                        // Text align and white sapce
                        if (text.textAlign == "justify") {
                            style += `text-align-last: justify;`;
                        }
                        if (/\s/g.test(text.text)) {
                            style += `white-space: pre;`;
                        }


                        // Background Color Layer
                        if (hasBGColor) {
                            let istop = false;
                            let totalTop;

                            if (text.fontFamily === "ChokoPlain" || text.fontFamily === "Choko Plain") {
                                istop = true;
                                totalTop = (text.height - text.fontSize) + 2;
                            }

                            if (text.fontFamily === "DelinquentCaps") {
                                istop = true;
                                totalTop = (text.height - text.fontSize);
                            }

                            let bgColor = document.createElement("span");
                            bgColor.setAttribute(
                                "style",
                                `
                                                position: absolute;
                                                transform: rotate(${text.angle}deg);
                                                transform-origin: top left;
                                                height: 100%;
                                                width: 100%;
                                                background-color: ${text.textBackgroundColor};
                                            `
                            );
                            // top: ${text.textBackgroundColor && !text.fill.type ? '3px' : '0px'}
                            // top: ${istop ? totalTop : '0'}
                            iText.append(bgColor);
                        }
                        iTextHolder.setAttribute("style", style);
                        style += `position: absolute;`;
                        iText.append(iTextHolder);
                        iText.setAttribute("data-id", text.id);
                        elements[text.index ? text.index : index] = iText;

                    }
                });
            }


            if (elements.length > 0) {
                elements.forEach((el) => {
                    div_el.appendChild(el);
                });
            }
        });
    </script>
</body>

</html>

expected Output

HTML output Expected Output

Higher Height output

0

There are 0 best solutions below