fillText(text, x, y[, maxWidth]) draws filled text directly onto a Canvas using the current font, fillStyle, textAlign, textBaseline, and text direction settings.
Unlike path methods, fillText() does not add text to the current path. Calling fill() later does not affect text already drawn.
const canvas = document.getElementById('text_basic');
const ctx = canvas.getContext('2d');
ctx.font = 'bold 36px sans-serif';
ctx.fillStyle = '#1456a0';
ctx.fillText('plus2net.com', 30, 75);
The optional maxWidth asks the browser to fit the rendered text within that width, for example by using a condensed face or scaling the text. It is not a clipping width.
ctx.font = '42px sans-serif';
ctx.fillText('A long Canvas label', 20, 70, 220);
const gradient = ctx.createLinearGradient(20, 0, 320, 0);
gradient.addColorStop(0, '#d7191c');
gradient.addColorStop(1, '#2c7bb6');
ctx.fillStyle = gradient;
ctx.font = '46px serif';
ctx.fillText('plus2net.com', 20, 80);
Use measureText() when layout depends on the actual text width rather than guessing character counts.
ctx.font = '24px sans-serif';
const metrics = ctx.measureText('Canvas text');
console.log(metrics.width);
Canvas text is painted as pixels and is not a replacement for semantic HTML text. If the words carry important content, provide the same information in normal HTML near the Canvas.
The current fillStyle controls the filled text color, gradient or pattern.
The y coordinate is positioned according to the current textBaseline setting, not necessarily the top of the letters.
No. For multi-line text, measure and draw lines yourself or use normal HTML when possible.
It asks the browser to fit the text within a maximum rendered width; it is not simply a clipping box.
fillText() paints the inside of glyphs with fillStyle; strokeText() paints their outlines with strokeStyle.
strokeText() | font | textAlign | textBaseline | fillStyle | Canvas tutorial
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.