Blog

Convert text to an image with Javascript and HTML5

Hello!

Working with frameworks like Django and with CMS’ like Drupal and WordPress we come across a wide variety of requirements for manipulating, sanitizing and importing data from all different sources and formats.

Recently we had the requirement to take a text field that was defined in a Django model and convert that text string to an image. There are many reasons for this type of requirement. You could argue that this requirement would be the first (of many) steps towards implementing your own custom captcha solution.

Well we did some research and found some solutions out there and implemented it our self in Django and we thought we’d share here as well! I’ll go through each of the components necessary to implement this. This type of implementation can very easily be integrated into WordPress or Drupal through a custom module or custom plugin or function perhaps. Additionally you can go beyond just “text” strings and you can draw boxes and manipulate the fill colors and create rudimentary graphics that are dynamically generated. This may be useful on pages with user generated content for example.

Javascript

 

To start, this javascript code is very simplistic. You could create a simple HTML file and manually fill in the fields that I have defined as template “tags” (for Django). You can see that I am defining a font and font size, which is useful. You can also set the color, background color and other variables within the code above, but I chose to keep it simple.

HTML5

To dynamically draw the graphics, we are going to use an HTML5 element called canvas. Canvas is designed to do just that – draw graphics on the fly. If your browser doesn’t support HTML5, you won’t see anything. You can put text in between the canvas tags so that browsers that do not support HTML5 will at least see a message.

Your browser does not support HTML5

You can see that I am setting a size as well as CSS styling such as padding, margins and width. This is our attempt to make the canvas element more responsive. There is more that would have to be done in order to accomplish this. You would have to define a css container for the canvas and apply some constraints and elements to that container. Then you would have to implement jquery code to trigger a function to apply certain elements to ensure the canvas container is responsive. I’ll leave that for another post!

In the end you will see that you can generate an image based on any text with many options to style it. I hope somebody finds this useful!