當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js textFont()用法及代碼示例

p5.j​​s中的textFont()函數用於指定將使用text()函數繪製文本的字體。在WEBGL模式下,僅支持loadFont()方法加載的字體。

用法:

textFont( font, size )

參數:該函數接受上述和以下描述的兩個參數:



  • font:它是一個字符串,用於指定Web安全字體的名稱或loadFont()函數加載的字體對象。
  • size:它是一個數字,指定要使用的字體的大小。它是一個可選參數。

返回值:它是一個包含當前字體的對象。

以下示例說明了p5.js中的textFont()函數:

範例1:本示例說明了所有係統上通常都可以使用的Web安全字體的用法。

function setup() { 
  createCanvas(600, 300); 
  textSize(30); 
  
  textFont('Helvetica'); 
  text('This is the Helvetica font', 20, 80); 
  textFont('Georgia'); 
  text('This is the Georgia font', 20, 120); 
  textFont('Times New Roman'); 
  text('This is the Times New Roman font', 20, 160); 
  textFont('Courier New'); 
  text('This is the Courier New font', 20, 200); 
}

輸出:
web-safe-fonts

範例2:本示例說明使用通過loadFont()函數加載的字體。

let newFont; 
  
function preload() { 
  newFont = loadFont('fonts/Montserrat.otf'); 
} 
  
function setup() { 
  createCanvas(400, 200); 
  textSize(20); 
  fill("red"); 
  text('Click once to print using " 
    + "a new loaded font', 20, 20); 
  fill("black"); 
  
  text('Using the default font', 20, 60); 
  text('This is text written using" 
        + " the new font', 20, 80); 
} 
  
function mouseClicked() { 
  textFont(newFont); 
  textSize(20); 
  text('Using the Montserrat font', 20, 140); 
  text('This is text written using the" 
       + " new loaded font', 20, 160); 
}

輸出:
load-font

在線編輯: https://editor.p5js.org/

環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/

參考: https://p5js.org/reference/#/p5/textFont




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js | textFont() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。