Grunt 下的精靈圖自動構建工具:grunt-img-sprite

fkd27 9年前發布 | 21K 次閱讀 前端技術 grunt-img-sprite

Grunt 下的精靈圖自動構建工具,基于 img-sprite 實現,依賴 GM

安裝

這個插件需要 Grunt~0.4.5

如果你還沒有使用過 Grunt,一定要查看入門指南,因為它解釋了如何創建一個 Gruntfile 以及安裝和使用 Grunt 插件。一旦你熟悉這個過程中,您可以安裝這個插件,使用此命令:

npm install grunt-img-sprite --save-dev

一旦插件被安裝,你可以在 Gruntfile 內配置這行JavaScript代碼:

grunt.loadNpmTasks('grunt-img-sprite');

特性

  1. 像 FIS 一般,通過在 css 文件中背景圖片添加標識合并精靈圖。跟平時一樣寫 css,僅在打包階段產出精靈圖和新的 css 文件
  2. 能夠根據標識產出多個精靈圖
  3. 不依賴 Less 等 CSS 預處理器
  4. 兼容 Retina,并自動插入媒體查詢代碼
  5. Base64 內聯圖片,通過?__inline標識

使用

簡單配置如下

Gruntfile

grunt.initConfig({
    img_sprite: {
        task: {
            src: 'css/main.css',
            dest: 'css/dest.css' }
    }
});
...

main.css

.icon0 {
  width: 128px;
  height: 128px;
  background: url(../images/0.png?__tom) no-repeat;
  background-size: 128px 128px;
}
.icon1 {
  width: 128px;
  height: 128px;
  color: #ccc;
  background: url(../images/1.png?__tom) no-repeat;
  background-size: 128px 128px;
}
.icon2 {
  width: 50px;
  height: 50px;
  color: #ccc;
  background: url(../images/2.png?__inline) no-repeat;
  background-size: 50px 50px;
}

css 文件

精靈圖

更多配置如下

grunt.initConfig({
    img_sprite: {
        options: {
            output: 'test/tmp/',
            imgPath: '../images/',
            prefix: 'sprite-',
            retina: false,
            algorithm: 'binary-tree',
            padding: 10,
            sizeLimit: 10 * 1024
        },
        task: {
            src: 'css/*.css',
            dest: 'dest/css'
        }
    },
});

參數

task.src

  • 類型:Array
  • 說明:css 文件路徑,必須
  • 默認:無

task.dest

  • 類型:String
  • 說明:css 產出路徑,當僅處理一個 css 文件時可指定文件名
  • 默認:當前目錄

options.output

  • 類型:String
  • 說明:精靈圖產出路徑
  • 默認:當前目錄

options.retina

  • 類型:Boolean
  • 說明:是否產出 @2x 圖片
  • 默認:true

options.padding

  • 類型:Number
  • 說明:精靈圖中圖片間距
  • 默認:10

options.prefix

  • 類型:String
  • 說明:精靈圖前綴;當產出 css 文件與指定 css 的目錄一致時,為 css 文件添加該前綴
  • 默認:'sprite-'

options.imgPath

  • 類型:String
  • 說明:css 文件中的圖片路徑
  • 默認:'../images/'

options.algorithm

  • 類型:String
  • 說明:圖片排序算法
  • 可選:top-down, left-right, diagonal, alt-diagonal, binary-tree
  • 默認:'binary-tree'

options.media

  • 類型:String
  • 說明:媒體查詢條件
  • 默認:only screen and (-webkit-min-device-pixel-ratio: 1.5)

options.sizeLimit

  • 類型:Number
  • 說明:內聯圖片大小限制
  • 默認:5000

項目主頁:http://www.baiduhome.net/lib/view/home/1445081602247

 本文由用戶 fkd27 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!