前言
前一篇介紹了 Container,接下來要來看介紹前一篇所使用到的語法,也就是 new PIXI.Text()
。
文字
許多時候我們會需要在畫面上寫字,那麼就會需要使用 new PIXI.Text()
這個方法,使用的方法非常簡單,在前面也已經示範過一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const app = new PIXI.Application({ view: document.getElementById('main'), width: 200, height: 200, antialias: true, transparent: false, backgroundColor: 0x00CC99, });
const container = new PIXI.Container(); app.stage.addChild(container);
const PIXIText = new PIXI.Text('這是一段話'); container.addChild(PIXIText);
|
字型風格
但是其實 new PIXI.Text('這是一段話')
還有其他的參數,假使來講若想要替文字設置字型,那就要在新增第二個物件參數 fontFamily
1 2 3
| const text = new PIXI.Text('這是一段話', { fontFamily: 'Microsoft JhengHei', })
|
此外字型大小、對齊方式以及字型顏色都可以設置
1 2 3 4 5 6
| const text = new PIXI.Text('這是一段話', { fontFamily: 'Microsoft JhengHei', fontSize: 24, fill: [0xEEEE00, 0x00ff99], align: 'center', })
|
字體外框
此外還有一些特別的屬性,你還可以替字體增加外框,概念就跟 CSS 中的 border 雷同
1 2 3 4 5 6 7 8
| const text = new PIXI.Text('這是一段話', { fontFamily: 'Microsoft JhengHei', fontSize: 24, fill: 0xEEEE00, align: 'center', stroke: '#000000', strokeThickness: 8, })
|
字體陰影
假使來講若希望字體有陰影,那麼當然 PIXI 也有相關設置
1 2 3 4 5 6 7 8 9 10 11 12 13
| const text = new PIXI.Text('這是一段話', { fontFamily: 'Microsoft JhengHei', fontSize: 24, fill: 0xEEEE00, align: 'center', stroke: '#000000', strokeThickness: 8, dropShadow: true, dropShadowColor: '#ffffff', dropShadowBlur: 4, dropShadowAngle: 5, dropShadowDistance: 10 })
|
字體換行
最後字體也可以設置換行以及寬度到多少就換行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const text = new PIXI.Text('這是一段話', { fontFamily: 'Microsoft JhengHei', fontSize: 24, fill: 0xEEEE00, align: 'center', stroke: '#000000', strokeThickness: 8, dropShadow: true, dropShadowColor: '#ffffff', dropShadowBlur: 4, dropShadowAngle: 5, dropShadowDistance: 10, wordWrap: true, wordWrapWidth: 150, })
|
另一種設置字型方式
最後介紹另一種設置字型的方式,有時候因為過多的物件都寫在同一個地方會顯得非常雜亂,所以 PIXI 有額外提供另一個關於 Text 的 API 是 TextStyle
,我們可以將第二個參數拉出來寫,這樣可以讓程式碼的可讀性高一點
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const style = new PIXI.TextStyle({ fontFamily: 'Microsoft JhengHei', fontSize: 24, fill: 0xEEEE00, align: 'center', stroke: '#000000', strokeThickness: 8, dropShadow: true, dropShadowColor: '#ffffff', dropShadowBlur: 4, dropShadowAngle: 5, dropShadowDistance: 10, wordWrap: true, wordWrapWidth: 150, }) const text = new PIXI.Text('這是一段話', style);
|
參考文獻