V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
50vip
V2EX  ›  程序员

1kb 的 placeholder.js 增加 img 标签使用方式

  •  
  •   50vip · 2015-12-21 11:38:48 +08:00 · 1361 次点击
    这是一个创建于 3054 天前的主题,其中的信息可能已经有所发展或是发生改变。

    预览

    官方网站示例项目 github 地址

    screenshots/website.png

    screenshots/with_chinese.png

    使用

    引入 placeholder.js 到你的前段代码中:

    <script src="placeholder.js"></script>
    

    1. 调用 placeholder.js 的方法进行替换,举个例子如下:

    <img src="image_origin.png" onerror="this.src=placeholder.getData({text: 'Image 404'})">
    

    2. 使用 URL 参数的方式配置 Img 的属性 options ,例如:

    <img class="placeholder" />
    

    或者携带参数 options:

    <img options="size=256x128&text=Hello!" class="placeholder" />
    

    请注意 img 标签的 class 属性必须 placeholder 。

    Placeholder 配置项

    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.
    • color: 前景颜色,文字颜色. 例如: #ccc. 默认: random.
    • 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 方法

    • placeholder.getData(opts): 获得 placeholder 图片的 base64 字符串,可以直接在 img 标签的 src 属性中使用,或者在 css 的背景中使用。
    • placeholder.getCanvas(opts): 获得 canvas 元素, 可以直接插入到 DOM 结构中。
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2469 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:33 · PVG 21:33 · LAX 06:33 · JFK 09:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.