官方網站示例、 項目 github 地址css
引入 placeholder.js 到你的前段代碼中:git
<script src="placeholder.js"></script>
1.
調用 placeholder.js 的方法進行替換,舉個例子以下:github
<img src="image_origin.png" onerror="this.src=placeholder.getData({text: 'Image 404'})">
2.
使用 URL 參數的方式配置 Img 的屬性 options ,例如:web
<img class="placeholder" />
或者攜帶參數 options:canvas
<img options="size=256x128&text=Hello!" class="placeholder" />
請注意 img 標籤的 class 屬性必須 placeholder 。dom
Placeholder 配置項用於 API 方法的輸入參數, e.g. placeholder.getData({text: 'Image 404'})
. 或者做爲 URL 參數樣式做爲 img 的屬性配置, e.g. options="size=256x128&text=Hello!"
字體
size
: placeholder 圖片尺寸. 例如: 256x128
, 默認: 128x128
.網站
bgcolor
: 背景顏色. 例如: #969696
. 默認: random
.this
color
: 前景顏色,文字顏色. 例如: #ccc
. 默認: random
.spa
text
: 自定義文本內容. 例如: Hello World, 你好
. 默認: equal to size
.
fstyle
: 字體樣式. 能夠是 normal / italic / oblique
. 默認: oblique
.
fweight
: 字體 weight. 能夠是 normal / bold / bolder / lighter / Number
. 默認: bold
.
fsize
: 字體大小. 默認: 自動
計算字體大小防止文字超出圖片大小.
ffamily
: 字體. 默認: consolas
.
具體參數配置例子:
var opts = { size: '512x256', bgcolor: '#ccc', color: '#969696', text: 'Hello World, 你好', fstyle:'oblique', fweight: 'bold', fsize:'40', ffamily: 'consolas' } console.log(placeholder.getData(opts)) //get the base64 of the placeholder image.
做爲 img 的 options 屬性爲:
size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&fsize=40&ffamily=consolas
placeholder.getData(opts)
: 得到 placeholder 圖片的 base64 字符串,能夠直接在 img 標籤的 src 屬性中使用,或者在 css 的背景中使用。
placeholder.getCanvas(opts)
: 得到 canvas 元素, 能夠直接插入到 DOM 結構中。