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

JS 获取文字实际宽度 #27

Open
zty012 opened this issue Oct 1, 2024 · 0 comments
Open

JS 获取文字实际宽度 #27

zty012 opened this issue Oct 1, 2024 · 0 comments
Labels

Comments

@zty012
Copy link
Owner

zty012 commented Oct 1, 2024

export function getTextSize(text: string, size: number): Vector {
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  if (!context) {
    throw new Error("Failed to get canvas context");
  }
  context.font = `${size}px system-ui`;
  const metrics = context.measureText(text);
  return new Vector(metrics.width, size);
}
@zty012 zty012 added the 前端 label Oct 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant