The HTML5 <canvas> element is a versatile tool that allows developers to draw shapes, images, and even text. In this guide, we will cover various ways to style and decorate text in a canvas, including basic rendering, gradients, shadows, outlines, and rotation.
1. Basic Text Rendering
You can render simple text using the ctx.fillText() method.
This technique first fills the text with a solid color and then applies an outline.
6. Rotated Text
You can also rotate text by saving the canvas state, applying transformations, and restoring the canvas:
// Basic text
ctx.font = "20px Arial";
ctx.fillStyle = "#2c3e50";
ctx.fillText("Basic Text", 50, 40);
// Gradient text
var gradient = ctx.createLinearGradient(50, 60, 300, 60);
gradient.addColorStop(0, "#e74c3c");
gradient.addColorStop(1, "#f1c40f");
ctx.font = "bold 24px Arial";
ctx.fillStyle = gradient;
ctx.fillText("Gradient Text", 50, 80);
// Shadow text
ctx.shadowColor = "rgba(0,0,0,0.3)";
ctx.shadowBlur = 4;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.font = "30px Georgia";
ctx.fillStyle = "#3498db";
ctx.fillText("Shadow Text", 50, 130);
// Reset shadow
ctx.shadowColor = "transparent";
// Outlined text
ctx.font = "36px Impact";
ctx.strokeStyle = "#9b59b6";
ctx.lineWidth = 2;
ctx.strokeText("Outlined Text", 50, 180);
// Outlined with fill
ctx.font = "bold 40px Verdana";
ctx.fillStyle = "#2ecc71";
ctx.strokeStyle = "#27ae60";
ctx.lineWidth = 2;
ctx.fillText("Filled & Outlined", 50, 240);
ctx.strokeText("Filled & Outlined", 50, 240);
// Rotated text
ctx.save();
ctx.translate(50, 300);
ctx.rotate(-Math.PI / 6);
ctx.font = "24px Comic Sans MS";
ctx.fillStyle = "#e67e22";
ctx.fillText("Rotated Text", 0, 0);
ctx.restore();
In this example, ctx.save() saves the current canvas state, ctx.translate() moves the origin, and ctx.rotate() rotates the canvas by -30 degrees. After drawing the text, ctx.restore() reverts the canvas to its original state.
Conclusion
HTML5 Canvas provides an extensive set of features for rendering and decorating text. Whether you're creating a game or a dynamic web application, mastering these text techniques can greatly enhance your canvas projects. Experiment with these methods and see what creative designs you can achieve!