在不知道字体系列的情况下更改Canvas的字体大小 [英] Change font size of Canvas without knowing font family

查看:258
本文介绍了在不知道字体系列的情况下更改Canvas的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以只更改画布上下文的字体大小而不必知道/编写字体系列。

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").getContext("2d");

 ctx.font = '20px Arial'; //Need to speficy both size and family...     

注意:

ctx.fontSize = '12px'; //doesn't exist so won't work...
ctx.style.fontSize = '20 px' //doesn't exist so won't work... 
                         //we are changing the ctx, not the canvas itself

其他说明:我可以做类似的事情:检测 px '是,删除'px'之前的内容并替换为我的字体大小。但是,我希望有比这更简单的方法。

Other note: I could do something like: detect where 'px' is, remove what's before 'px' and replace it by my font size. But I'd like something easier than that if possible.

推荐答案

更新:(来自注释)没有办法指定字体。画布的字体以CSS中字体的简写形式为模型。

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;

然后替换size参数并将其重新设置(请注意,那里也可能有样式参数)

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

如果需要,您将需要样式的支持(IIRC首先出现用过的)。
请注意,font-size是第四个参数,因此如果您具有/不具有font-variant(粗体,斜体,斜角),font-variant(普通,小写)和font-weight,则此功能将不起作用(粗体等)。

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

这篇关于在不知道字体系列的情况下更改Canvas的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆