Tag Archives: word art

HTML5 textured word art using canvas


CSS methods of creating a texture for words normally involves creating an image that has a transparency and placing it on top of the text. This method has many limitations. Canvas allows image processing on the fly and can create much richer textures. Here is an example for gold lettering.

<!DOCTYPE html>
<html>
<head>
<title>wsmithdesign, textured word art using canvas </title>

</head>

<body>

<img src=”gold-texture.jpg” width=”1″ id=”gold” />

<div style=”background:#224488″ id=”areawrap”>
<canvas id=”area” width=”550″ height=”75″>
<h1>Path Ways Learning</h1>
</canvas>
</div>

<script>

window.onload = function() {

We need to wait until the graphics is loaded.

// first we write the text.
var canvas = document.getElementById(“area”);
var context = canvas.getContext(“2d”);

When the letters are rendered onto the canvas the edges are softened but a transparency may not used with all browsers; so we will need to process the image to recreate the transparency. We will do this by writing red text on a black background the color red will then be our mask and set the transparency on the edges.

// recreate transparency layer

context.fillStyle =”#000000″;
context.fillRect(0,0,550,75);

context.font =  “40px Ariel”;
context.fillStyle = “#ff0000”;
context.fillText(“Path Ways Learning”, 10, 50);

Now the text image is created and ready to be processed.

// get text
var lettersImage = context.getImageData(0, 0, 550, 75);
var pix = lettersImage.data;

The texture will be the gold leaf image.

// get texture
var gold = document.getElementById(“gold”);
context.drawImage(gold, 0, 0, 550, 75);
var goldImage = context.getImageData(0, 0, 550, 75);
// Image must be on same domain as html!
var colors = goldImage.data;

Now we create an image using our texture and the red channel of the lettering for our transparency.

// apply texture to lettersImage

for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i+3] = pix[i];
pix[i  ] = colors[i  ] ;     // red
pix[i+1] = colors[i+1] ;     // green
pix[i+2] = colors[i+2] ;     // blue

}

Draw the completed image.

context.putImageData(lettersImage, 0, 0);

}
</script>
</body>
</html>

Advertisements