簡體   English   中英

導入的字體在 Chrome 中有效,但在 Safari 中無效

[英]Imported Font Works In Chrome but not Safari

我一直在 Chrome 中測試我的網站,並且一切都按預期工作,但我剛剛發現我的字體沒有在 Safari 中導入,並且使用了默認字體而不是我應該使用的字體。 我包含了一個片段,顯示了我如何導入和使用字體 - 也許我需要以不同的方式訪問字體才能讓它在兩個瀏覽器中都可用?

 const context = document.querySelector("canvas").getContext("2d"); context.width = document.body.clientWidth; context.height = document.body.clientHeight; context.beginPath(); context.font = "10vw Montserrat"; context.fillStyle = "red"; context.textAlign="center"; context.textBaseline = "middle"; context.fillText("XXXXXX", context.width/2, context.height/2); context.closePath();
 @import url('https://fonts.googleapis.com/css?family=Montserrat:900i&display=swap');
 <canvas class="game"></canvas>

只有在您的 DOM 中實際使用了 webfont 時才會加載它。
您可以在 chromes 開發工具網絡選項卡中檢查這一點。
(我認為它適用於 Chrome,因為您可能在本地安裝了“Montserrat”)。

為確保字體已加載,您可以通過 js FontFace()方法加載它。

工作示例

 const canvas = document.querySelector("canvas"); const context = canvas.getContext("2d"); context.width = document.body.clientWidth; context.height = document.body.clientHeight; let fontUrl = "https://fonts.gstatic.com/s/montserrat/v24/JTUFjIg1_i6t8kCHKm459Wx7xQYXK0vOoz6jqw16WXh0pg.woff2"; let fontFamily = "Montserrat"; let fontOptions = { weight: 900, style: "italic" }; loadFonts(fontFamily, fontUrl, fontOptions); async function loadFonts(fontFamily, fontUrl, fontOptions) { const font = new FontFace(fontFamily, `url(${fontUrl})`); font.weight = fontOptions.weight ? fontOptions.weight : 400; font.style = fontOptions.style ? fontOptions.style : "normal"; // wait for font to be loaded await font.load(); document.fonts.add(font); // apply font styles to canvas canvas.classList.add("fonts-loaded"); canvas.setAttribute( "style", `font-family:${fontFamily}; font-weight:${fontOptions.weight}; font-style:${fontOptions.style}` ); drawText(); } function drawText() { context.font = "48px Montserrat"; context.fontWeight = 900; context.fontStyle = "italic"; context.fillStyle = "red"; context.textAlign = "center"; context.textBaseline = "middle"; context.fillText("Hamburg", 150, 50); }
 canvas { height: 50vh; border: 1px solid red } .fonts-loaded { border: 1px solid green; }
 <canvas class="game" />

  1. 我們正在異步函數中加載字體文件
    (只需打開 google 字體 css(例如https://fonts.googleapis.com/css?family=Montserrat:900i )以獲取實際的字體文件 url)
  2. 加載字體后,我們通過設置內聯樣式將所需的字體樣式屬性應用於canvas元素(您也可以使用類)
  3. 現在我們可以在畫布上繪制文本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM