Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

为什么 App 端 Canvas 设置 font 时不支持小数像素? #5329

Open
toFrankie opened this issue Mar 5, 2025 · 1 comment
Open

为什么 App 端 Canvas 设置 font 时不支持小数像素? #5329

toFrankie opened this issue Mar 5, 2025 · 1 comment
Labels
question Further information is requested

Comments

@toFrankie
Copy link

问题分类

uni-app

问题描述

在 App 端使用 Canvas 设置文本样式时,

发现 fontSize 不支持小数像素。

canvasContext.font = 'normal 400 12px system-ui' ✅
canvasContext.font = 'normal 400 12.5px system-ui' ❌

会抛出 Warning,进而不会设置文本样式。

10:37:32.549 Failed to set 'font' on 'CanvasContext': invalid format. __WARN

翻看源码发现是 set font 里的正则表达式无法匹配到小数像素。

var fontFormat = value.match(
  /^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/
)

匹配示例:https://regexr.com/8cpbq

请问是出于什么考虑不支持小数像素?

有时候需要绘制文本,如果先经过 Math.round(originalPixel) 等处理,有时实际绘制出来的文本会预期的的“粗”或“细”,因此希望可以支持小数像素。

附加信息

No response

@toFrankie toFrankie added the question Further information is requested label Mar 5, 2025
@toFrankie
Copy link
Author

另外,对于 fontWeight 为什么只支持 normal、bold 两者,而不支持 500、600、700 这类数值。

// ...
else if (['bold', 'normal'].indexOf(value) > -1) {
  actions.push({
    method: 'setFontWeight',
    data: [value],
  })
  self.state.fontWeight = value
}

源码

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant