Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Text to Image using javascript [closed]

Is there any way I can convert the input text into an image. What I am exactly trying to do is type some text into a textbox and display it on div. When I click on a button the text copied to div should be changed to an image. Does anyone know anything about this? Thanks in advance!

like image 342
Shab Avatar asked Sep 08 '12 06:09

Shab


2 Answers

You can do this using a hidden canvas element and converting that to an image using toDataURL. Your code would look something like this:

var tCtx = document.getElementById('textCanvas').getContext('2d'), //Hidden canvas     imageElem = document.getElementById('image'); //Image element    // Text input element document.getElementById('text').addEventListener('keyup', function() {   tCtx.canvas.width = tCtx.measureText(this.value).width;   tCtx.fillText(this.value, 0, 10);   imageElem.src = tCtx.canvas.toDataURL();   console.log(imageElem.src); }, false);
canvas{     border: 1px black solid; } #textCanvas{     display: none; }
<canvas id='textCanvas' height=20></canvas> <img id='image'> <br> <textarea id='text'></textarea>

Demo

like image 136
Some Guy Avatar answered Oct 09 '22 11:10

Some Guy


The canvas approach suggested by Amaan is definitely today's approach to generating images client-side.

In the past, the most common solution was to use a library like Cufon. From the Cufon wiki page on its usage comes this snippet:

<script type="text/javascript">     Cufon.replace('h1'); // Works without a selector engine     Cufon.replace('#sub1'); // Requires a selector engine for IE 6-7, see above </script> 

Cufon generates the client-side version of the font up-front. This means it just adds static files on your web server, instead of generating the images on the web server (like with ImageMagick).

like image 24
Frank van Puffelen Avatar answered Oct 09 '22 12:10

Frank van Puffelen