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

iOS 端 Canvas 设置 font-weight 问题 #5337

Open
gd4Ark opened this issue Mar 11, 2025 · 1 comment
Open

iOS 端 Canvas 设置 font-weight 问题 #5337

gd4Ark opened this issue Mar 11, 2025 · 1 comment
Assignees

Comments

@gd4Ark
Copy link

gd4Ark commented Mar 11, 2025

发行方式

App

具体平台

iOS

开发环境

macOS

项目创建方式

HBuilderX

依赖版本

3.0.0-4050320250303001

问题描述

ctx.font = 'bold 20px Arial'
ctx.fillText(`对比 ${ctx.font}`) // 20px Arial

如上所示,在 iOS 端会丢失 bold 效果,这个问题应该与 Safari 浏览器这个问题一致:https://stackoverflow.com/questions/51440257/safari-missing-font-weight-component-when-retrieving-font-property-from-canvas

然后在 fillText 时会重新赋值一下 ctx.font

var font = this.font
this.font = font.replace(
/(\d+\.?\d*)(px|em|rem|pt)/g,
function (w, m, u) {
return m * pixelRatio + u
}
)

该问题会导致在 iOS App 端、H5 端 Safari 浏览器上绘制 canvas 文本时,丢失加粗效果。

重现步骤

将以下代码分别编译到 iOS App 端、H5 端 Safari 浏览器下预览:

<template>
  <canvas
    id="myCanvas"
    canvas-id="myCanvas"
    class="canvas"
    :style="{
      width: `${CANVAS_WIDTH}px`,
      height: `${CANVAS_HEIGHT}px`
    }"
  />
</template>

<script>
export default {
  data() {
    return {
      CANVAS_WIDTH: 550,
      CANVAS_HEIGHT: 550
    }
  },
  onReady() {
    const ctx = uni.createCanvasContext('myCanvas')

    ctx.fillStyle = '#000'

    let y = 0

    ctx.font = 'normal 20px Arial'
    ctx.fillText(`对比 ${ctx.font} 1`, 10, (y += 30))

    ctx.font = 'normal normal normal 20px Arial'
    ctx.fillText(`对比 ${ctx.font} 2`, 10, (y += 30))

    ctx.font = 'bold 20px Arial'
    ctx.fillText(`对比 ${ctx.font} 3`, 10, (y += 30))

    ctx.font = 'normal normal bold 20px Arial'
    ctx.fillText(`对比 ${ctx.font} 4`, 10, (y += 30))

    ctx.font = '20px Arial'
    ctx.fillText('对比基准 5', 10, (y += 30))

    ctx.draw()
  },
}
</script>

期望行为

加粗效果不应丢失

实际行为

No response

截图或录屏

No response

@Otto-J Otto-J self-assigned this Mar 11, 2025
@Otto-J
Copy link
Member

Otto-J commented Mar 12, 2025

如昨天沟通,在 safari 中给 canvvasCtx.font 赋值,然后读取会发现丢失 font-weight, 看起来不是 uniapp 的问题。

如果考虑兼容这个问题,实际可以针对 font__font__ 不一致时候,读取 __font__ 从而临时绕过此问题。感兴趣可以提一个 PR

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

No branches or pull requests

2 participants