Canvas
This example utilizes the canvas element instead of CSS as per the request.
By clipping the image with text and adding a shadow, you can achieve the following effect:
Example
Check out the LIVE DEMO HERE
Here is the result:
/// set text settings
ctx.textBaseline = 'top';
ctx.font = '150px impact';
ctx.textAlign = 'center';
/// draw the text
ctx.fillText(txt, demo.width * 0.5, 10);
To clip the image using the text and add a shadow, follow these steps:
/// change composite mode to fill text
ctx.globalCompositeOperation = 'source-in';
/// draw the image on top, it will be clipped by the text
ctx.drawImage(img, 0, 0);
To add a shadow, reset the composite mode, set the shadow, and draw the canvas back to itself:
We use the save
and restore
methods to simplify the process.
/// reset composite mode to normal
ctx.globalCompositeOperation = 'source-over';
/// create a shadow by setting shadow...
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.5)';
ctx.shadowBlur = 7;
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
/// ... and drawing it back
ctx.drawImage(demo, 0, 0);
ctx.restore();
In the demo, a loop changes the text dynamically. The background is transparent, allowing the canvas to overlay other elements.
To make the code more reusable, refactor it into a universal function. Place all settings inside the function and use save
at the beginning and restore
at the end to preserve external settings.