简体   繁体   English

在 Canvas 文本上设置字体粗细

[英]Setting font-weight on Canvas text

I'm trying to write text over an image using the Canvas Element.我正在尝试使用 Canvas 元素在图像上书写文本。

I've set the font-weight to 900, but on mobile it doesn't show up.我已将字体粗细设置为 900,但在移动设备上它没有显示。

On desktop it's fine and even testing it within responsive mode it looks fine, but when I make it live, the heavier font-weight doesn't come through on my phone.在桌面上它很好,甚至在响应模式下测试它看起来很好,但是当我让它上线时,较重的字体粗细不会出现在我的手机上。

I tried the code snippet in the comments of Debug JS modifying some specific canvas element to debug it and I found that for some reason the ctx.font was only storing the font size and font name, but not the font weight.我尝试了Debug JS 的注释中的代码片段修改一些特定的 canvas 元素来调试它,我发现由于某种原因ctx.font只存储字体大小和字体名称,而不是字体粗细。

I added the word bold and it would store that, but not bolder or a number value.我添加了bold这个词,它会存储它,但不会存储bolder或数字值。

Does anyone have any idea what is going on here?有谁知道这里发生了什么?

I've included a code snippet and a screenshot from my debugging that shows how it's storing the font value.我已经包含了一个代码片段和我的调试屏幕截图,显示了它如何存储字体值。

截屏

function main() {
  // Put template on canvas
  ctx.drawImage(img, 0, 0, size, size);

  ctx.font = "bold 110px 'Saira Condensed', sans-serif";
  ctx.textAlign = "center";
  ctx.fillStyle = "#ffffff";
  ctx.fillText(number, 325, 290);
}

Chrome and Safari require that the font-style is also set in order to use a numerical value for font-weight : Chrome 和 Safari 还要求设置font-style以便为font-weight使用数值:

 const canvas = document.querySelector( "canvas" ); const ctx = canvas.getContext( "2d" ); // add 'normal' font-style ctx.font = "normal 900 24px Unknown, sans-serif"; ctx.fillText( "bold", 50, 50 ); ctx.font = "24px Unknown, sans-serif"; ctx.fillText( "normal", 150, 50 );
 canvas { background: white }
 <canvas></canvas>

When I tried this on Chrome (109.0.5414.87), numbered font-weights are converted to keywords.当我在 Chrome (109.0.5414.87) 上尝试这个时,编号的字体粗细被转换为关键字。 100 to 600 are converted to "normal" and disappeared, and 700 - 900 are converted to "bold". 100 到 600 转换为“正常”并消失,700 到 900 转换为“粗体”。

var context = document.createElement("canvas").getContext("2d");
context.font = "100 16px Arial" 
console.log(context.font) // prints "16px Arial"


context.font = "700 16px Arial" 
console.log(context.font) // prints "bold 16px Arial"

I've set the font-weight to 900, but on mobile it doesn't show up.我已将 font-weight 设置为 900,但在移动设备上它不显示。

On desktop it's fine and even testing it within responsive mode it looks fine在桌面上它很好,甚至在响应模式下测试它看起来也很好

Can you check that link?你能检查那个链接吗? I'm not sure is it related your problem but It can help: https://www.w3schools.com/html/html_images_picture.asp我不确定它是否与您的问题有关,但它可以提供帮助: https : //www.w3schools.com/html/html_images_picture.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM