Change font size of Canvas without knowing font family

前端 未结 5 988
遥遥无期
遥遥无期 2020-12-30 00:06

Is there a way to only change the font size of a canvas context without having to know/write the font family.

 var ctx = document.getElementById(\"canvas\").         


        
相关标签:
5条回答
  • 2020-12-30 00:11

    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).

    0 讨论(0)
  • 2020-12-30 00:11

    A cleaner way to not worry about scraping every other parameter:

    canvas.style.font = canvas.getContext("2d").font;
    canvas.style.fontSize = newVal + "px";
    
    canvas.getContext("2d").font = canvas.style.font;
    
    0 讨论(0)
  • 2020-12-30 00:15

    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;
    
    0 讨论(0)
  • 2020-12-30 00:17

    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");
    
    0 讨论(0)
  • 2020-12-30 00:26

    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.

    0 讨论(0)
提交回复
热议问题