2

I am new to this. I am just trying to get a single line of text to be converted to an image.

This is the 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>

This is the line of code I wish to covert to an image and display the image in a div on button click

    </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>
granch
  • 225
  • 3
  • 12
A.Ban
  • 43
  • 1
  • 1
  • 6
  • 1
    Possible duplicate of [Convert HTML5 canvas to IMG element](http://stackoverflow.com/questions/18008473/convert-html5-canvas-to-img-element) – Gabe Rogan May 11 '17 at 02:39

2 Answers2

9

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>
alessandrio
  • 4,282
  • 2
  • 29
  • 40
2

Your question is not very clear, but I suppose the method you're looking for is to draw the text onto a canvas, which you can then right-click on and save the image. Here's a snippet to get you started:

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

(You'll need to create a canvas with the id set to "myCanvas")

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Alex Jone
  • 292
  • 2
  • 14