Adding dynamic text to a responsive image (sort of)

Let's talk about HTML Canvas.

HTML 5 defines the <canvas> element as…

a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.

Put simply. A canvas is a rectangle in your page where you can use JavaScript to draw anything you want. We're going to use it to add dynamic text to an image.

First we need to create ourselves some basic HTML.

<canvas id="canvas" width="800" height="600"></canvas>  

Add some CSS to go with it.

#canvas { width: 100%; height: auto; max-width: 800px; background: red; }

You'll notice we've given it a red background. This is just so we can see our Canvas element for now, otherwise it would be invisible.

Now we move onto the JS.

// First we create a variable that grabs the canvas by it's ID
var theCanvas = document.getElementById('canvas');

// Then we use the getContext() method to return a drawing context on the canvas, in this case 2D
var theContext = theCanvas.getContext('2d');

// Now we create an image variable
var theImg = new Image();

This is the basic code needed to set up our Canvas stage. We're now ready to start adding items to the Canvas.

// We use the onload function so that we only begin to add content to the stage once the image has loaded
theImg.onload = function() {  
    // Let's set up the image, theImg variable, it's X, Y position and it's dimensions
    theContext.drawImage(theImg, 0, 0, 800, 600)
    // Setting up the font styling
    theContext.font = 'normal 13px Arial';
    theContext.fillStyle = '#ffffff';
    // To add the text to the Canvas we first define the text, then set it's position using X and Y parameters.
    theContext.fillText('Hello world!', 200, 100);
};

We've now added the text to our stage, but still we only have a red background. That's because we set up the image variable earlier, but we've still not told it what image we need to load. We'll do this next.

theImg.src = '/path/to/image.jpg';  

N.B. This has to be outside the onload() function

If you want the text to be dynamic, it's simple, you can swap the Hello World! for a prepopulated JS variable.

And that should be it.

You can see the working Codepen below: