skip to Main Content

I am trying to display normal HTML to load as an image on my page.
For example:

<h1>Hello World</h1>

This will display text on my page.
How do I convert this so that the h1 tag will display "Hello World" as an image on my page?

Any help would be greatly appreciated.

2

Answers


  1. I think you could use canvas element to render an image. More documentation here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas

    <canvas id="myCanvas" width="300" height="150" style="border:1px solid grey;">
    Sorry, your browser does not support canvas.
    </canvas>
    
    <script>
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");
    
    ctx.font = "50px Arial";
    ctx.fillText("Hello World",10,80);
    </script>
    Login or Signup to reply.
  2. I think the easiest way would be to add the text to a hidden canvas tag, then use toDataURL.

    The javascript:

    var cnvs = document.getElementById('cnvs').getContext('2d');
    var img = document.getElementById('img');
      
    document.getElementById('txt').addEventListener('keyup', function()
    {
      cnvs.canvas.width = cnvs.measureText(this.value).width;
      cnvs.fillText(this.value, 0, 10);
      img.src = cnvs.canvas.toDataURL();
    }, false);
    

    The css:

    #cnvs
    {
     display: none;
    }
    

    The html:

    <canvas id='cnvs'></canvas>
    <img id='img'/>
    <br/>
    <textarea id='txt'></textarea>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search