Build an Image Generator with html2canvas

March 18, 2016

With the enormous ecosystem of photo-editing tools available, it's no surprise that photo manipulation has become a weapon of choice for aspiring political satirists this election cycle. But the high cost of professional tools like Photoshop and the prohibitive learning curve of graphic design raise the barriers to entry to produce images like these. Many developers, sensing opportunity in this knowledge gap, have built tools that make it easier to caption images and produce commonly shared memes.

When Time Magazine put Marco Rubio on the cover in February 2013, calling him "The Republican Savior," the image was just begging for snarky photoshop shenanigans. I put together an image generator in CodePen allowing users to make their own Marco cover. If you've got some front-end development skill, you can build an image generator, too (this tutorial assumes some familiarity with HTML, CSS, JavaScript, and jQuery). A jQuery plugin called html2canvas makes them relatively straightforward to build.

Here's how.

Step 1: Preparation and dependencies

We'll need to create an HTML file, a CSS stylesheet, and a JavaScript script. We'll need to link the stylesheet and script in our HTML, along with two dependencies—jQuery and html2canvas.

Fortunately, CloudFlare's provides both dependencies as CDNs. So we can put them right into our HTML:


Now we're ready to start building the HTML structure.

Step 2: HTML

Before we dive into the jQuery, let's think about all the pieces we'll need for our generator and have them ready-built so they're good to go when we start implementing the script.

We want the user to be able to type a message, watch as that message is dynamically appended to the background image, and then press a button to take a 'screenshot' that turns the message and the background image into a new image the user can save.

So, we're going to need:

  • An input where the user can type in their message and submit it to generate the image
  • An image preview section where text from the input is appended as the user types, so the user can see what their image will look like
  • A method of delivering the newly created image to the user—either in a new browser tab or in a section of the current tab

For that last one, in order to avoid dealing with security restraints involved in opening a new tab on a user's browser, we'll use a simple lightbox overlay that shows the new image.

                     Save PNG Image                 

          Default text here