Change font size of Canvas without knowing font family

前端 未结 5 1033
遥遥无期
遥遥无期 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).

提交回复
热议问题