Change font size of Canvas without knowing font family

Update: (from comments) There is no way around specifying font. The Canvas' font is modeled after the short-hand version of font in CSS.

However, there is always a font set on the canvas (or a font type) so what you can do is to first extract the current font by using it like this:

var cFont = ctx.font;

Then replace size arguments and set it back (note that there might be a style parameter there as well).

A simple split for the sake of example:

var fontArgs = ctx.font.split(' ');
var newSize = '12px';
ctx.font = newSize + ' ' + fontArgs[fontArgs.length - 1]; /// using the last part

You will need support for style if needed (IIRC it comes first if used). Notice that font-size is fourth parameter, so this will not work if you will have/not have font-variant(bold,italic,oblique), font-variant(normal, small-caps) and font-weight(bold etc).


Here is an easier and cleaner way of changing the font size that will work regardless if you are using font-variant or font-weight or not.

Assuming your new font size is 12px

ctx.font = ctx.font.replace(/\d+px/, "12px");

Or a nice one liner if you want to increase by 2 points:

ctx.font = ctx.font.replace(/\d+px/, (parseInt(ctx.font.match(/\d+px/)) + 2) + "px");

try this (using jquery):

    var span = $('<span/>').css('font', context.font).css('visibility', 'hidden');
    $('body').append(span);
    span[0].style.fontWeight = 'bold';
    span[0].style.fontSize = '12px';
    //add more style here.
    var font = span[0].style.font;
    span.remove();
    return font;

To correctly answer your question, there is no way to change the font size of a canvas context without having to know/write the font family.