跳到主要內容

gulp 前端自動化 - spritesheet

大家好,我是奶綠茶
今天來介紹如何使用 gulp 來自動化將圖片拼成 spritesheet
奶綠我使用的套件是 gulp.spritesmith
https://www.npmjs.com/package/gulp.spritesmith
可以使用 handlebars 格式,拼出自己想要的 css 格式

{{#sprites}}
.{{name}} {
    background-position: {{px.offset_x}} {{px.offset_y}};
    width: {{px.width}};
    height: {{px.height}};
    background-image: url({{{escaped_image}}});
}
{{/sprites}}

gulp 的設定

gulp.task('sprite',()=>{
    console.log('sprite');
    const spriteData = gulp.src('src/sprite_src/*')
        .pipe(spritesmith({
            imgName: '../img/sprite.png',
            cssName: '_sprite.css',
            padding: 4,
            imgOpts: { quality: 100 },
            cssTemplate: 'src/css/handlebars/basic.handlebars',
        }));
    const imgStream = spriteData.img
        .pipe(buffer())
        .pipe(gulp.dest('dist/img/'));

    const cssStream = spriteData.css
        .pipe(gulp.dest('src/css'));
    return merge(imgStream, cssStream);
});
發佈後,就會產生對映的圖片和css檔

問題
在製作按鈕圖案時,都會把一般和hover的圖合拼在一張
這樣在 :hover 時只要指定 background-position:bottom 就可以
但現在經過合拼成 spritesheet 時,background-position 座標會有問題
所以我們來修正一下
在合拼時,判斷如果檔名有 _btn 就套用新的規則
新增 ifIndexOfBTN 表籤,加入自定的函式

{{#sprites}}
{{#ifIndexOfBTN name}}
.{{name}} {    
    background-position: {{px.offset_x}} {{px.offset_y}};
    width: {{px.width}};
    height: {{half height}};    }
    .{{name}}:hover {   background-position:{{px.offset_x}} {{hoverPosition offset_y height}};   }
{{else}}
.{{name}} {    
    background-position: {{px.offset_x}} {{px.offset_y}};
    width: {{px.width}};
    height: {{px.height}};  }

{{/ifIndexOfBTN }}
{{/sprites}}

更新gulp

.pipe(spritesmith({
 略 
 cssTemplate: 'src/css/handlebars/basic.handlebars',
 cssHandlebarsHelpers: {
  ifIndexOfBTN(name, options) {
   if (name.indexOf('_btn') !== -1) {
    return options.fn(this);
   }
   return options.inverse(this);
  },
  hoverPosition(position, height) {
   return `${position - (height / 2)}px`;
  },
  half(num) {
   return `${Math.floor(num / 2)}px`;
  },
 },
}));

handlebar 遇到自定的 tag 或是函式時
就會到 spritesmith 裡的 cssHandlebarsHelpers 去找對映的函式
完成。


轉載請註明出處
Github Source Code

留言