【问题标题】:Converting HTML text to an Image- Javascript将 HTML 文本转换为图像 - Javascript
【发布时间】:2017-10-09 21:00:15
【问题描述】:

我是新手。我只是想将单行文本转换为图像。

这是javascript

<!doctype html>
<html>
    <head>
        <title>Html to image</title>    
        <script type="text/javacript">
            $(function () {
                $("#show_img_btn").click(function () {
                    html2canvas("#the_text", {
                        onrendered: function (canvas) {
                            $("<img/>", {
                                id: "image",
                                src: canvas.toDataURL("image/png"),
                                width: '95%',
                                height: '95%'
                            }).appendTo($("#show_img_here").empty());
                        }
                    });
                });
            });
        }
        </script>

这是我希望转换为图像并在按钮单击时将图像显示在 div 中的代码行

    </head>
    <body>
        <div id="the_text">Hey! Im a text! I will be converted to an image</div>
        </br>

        <button id="show_img_btn">Convert to Image</button>
        <div id="show_img_here"></div>
    <body>
</html>

【问题讨论】:

标签: javascript html canvas


【解决方案1】:

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);
  });
};
canvas{
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
</head>
<body>
<div id="the_text">Hey! Im a text! I will be converted to an image</div>
<button id="show_img_btn">Convert to Image</button>
<div id="show_img_here"></div>
</body>

【讨论】:

    【解决方案2】:

    您的问题不是很清楚,但我想您正在寻找的方法是将文本绘制到画布上,然后您可以右键单击并保存图像。这是一个帮助您入门的 sn-p:

    var canvas = document.getElementById("myCanvas").getContext("2d");
    canvas.font = "30px Arial";
    var text = document.getElementById("the_text").innerHTML;
    canvas.fillText(text,10,50);
    

    (您需要创建一个 id 设置为“myCanvas”的画布)

    【讨论】:

    • 画布没有被填充
    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    相关资源
    最近更新 更多