【问题标题】:converted text into image using canvas display long text使用画布将文本转换为图像显示长文本
【发布时间】:2020-07-12 19:09:06
【问题描述】:

我在几个将文本转换为图像的案例中见过,但没有人提到如果文本太长,即超过 1000 个字,我如何使用 15px 的字体大小在图像中显示它们
我的 HTML 代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
</head>
<body>
<div id="the_text"></div>
<button id="show_img_btn">Convert to Image</button>
<div id="show_img_here"></div>
</body>

我的脚本代码

window.onload=function(){
  $("#show_img_btn").on("click", function () {
    var canvas = document.createElement("canvas");
    canvas.width = 620;
    canvas.height = 80;
    var ctx = canvas.getContext('2d');
    ctx.font = "30px Arial";
    var text = $("#the_text").text();
    ctx.fillText(text,10,50);
    var img = document.createElement("img");
    img.src=canvas.toDataURL();
    $("#show_img_here").append(img);
    //$("body").append(canvas);
  });
};

我的问题是,如果我转换此图像,它将转换为一行帮助我如何将整个文本转换为图像并设置高度和宽度。

【问题讨论】:

    标签: javascript jquery image-processing canvas canvasjs


    【解决方案1】:

    创建一个虚拟元素并应用相同样式的道具,附加到 dom 并获取它的 with。基于此,您可以拆分文本。下面给出了有用的 sn-p。

    // JS:

    function getDimen(text) {
        var div = document.getElementById("dummy");
        div.innerHTML = text
        var h = (div.clientHeight + 1) + "px";
        var w = (div.clientWidth + 1) + "px"
        return({ h, w })
    }
    console.log(getDimen("some text hi a a s a a s as a s as a s as a s as a s"))
    

    // HTML

    <div id="dummy"></div>
    

    // CSS:

    #dummy {
        position: absolute;
        visibility: hidden;
        height: auto;
        width: auto;
        white-space: nowrap;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      相关资源
      最近更新 更多