相信做前端的同學都做過這樣的事情,為優化圖片,減少請求會把拿到切好的圖標圖片,通過ps(或者其他工具)把圖片合並到一張圖里面,再通過css定位把對於的樣式寫出來引用的html里面。對於一些圖片較多的項目,這個過程可能要花費我們一天的時間,來實現這步。今天我給大家帶來一個工具,將這一步縮短到幾秒鍾就能完成,究竟是什么工具這么神奇呢,他就是gulp的一個插件gulp.spritesmith。下面一張圖來說明他能做什么。
看到這個圖片介紹,相信大家已經對gulp.spritesmith能做到什么一目了然了,其他的不多說,下面說直接實現
前期准備
安裝gulp(使用簡介)
后台命令安裝 gulp插件 :
npm install --save-dev gulp.spritesmith 安裝 gulp.spritesmith
Gulpfile.js 文件內容
/引入gulp var gulp=require("gulp"), spritesmith=require('gulp.spritesmith'); gulp.task('default', function () { return gulp.src('images/*.png')//需要合並的圖片地址 .pipe(spritesmith({ imgName: 'sprite.png',//保存合並后圖片的地址 cssName: 'css/sprite.css',//保存合並后對於css樣式的地址 padding:5,//合並時兩個圖片的間距 algorithm: 'binary-tree',//注釋1 cssTemplate:"css/handlebarsStr.css"//注釋2 })) .pipe(gulp.dest('dist/')); });
注釋一:
Algorithm 有四個可選值分別為top-down、left-right、diagonal、alt-diagonal、binary-tree
對於如下:
注釋二:
cssTemplate 是生成css的模板文件可以是字符串也可以是函數。是字符串是對於相對於的模板地址 對於模板文件樣式格式是:
{{#sprites}} .icon-{{name}}{ background-image: url("{{escaped_image}}"); background-position: {{px.offset_x}} {{px.offset_y}}; width: {{px.width}}; height: {{px.height}}; } {{/sprites}}
如果是函數的話,這可以這樣寫
//引入gulp var gulp=require("gulp"), spritesmith=require('gulp.spritesmith'); gulp.task('default', function () { return gulp.src('images/*.png')//需要合並的圖片地址 .pipe(spritesmith({ imgName: 'sprite.png',//保存合並后圖片的地址 cssName: 'css/sprite.css',//保存合並后對於css樣式的地址 padding:5,//合並時兩個圖片的間距 algorithm: 'binary-tree',//注釋1 cssTemplate: function (data) { var arr=[]; data.sprites.forEach(function (sprite) { arr.push(".icon-"+sprite.name+ "{" + "background-image: url('"+sprite.escaped_image+"');"+ "background-position: "+sprite.px.offset_x+"px "+sprite.px.offset_y+"px;"+ "width:"+sprite.px.width+";"+ "height:"+sprite.px.height+";"+ "}\n"); }); return arr.join(""); } })) .pipe(gulp.dest('dist/')); });
以上就是實現將css代碼中的切片圖片合並成雪碧圖的實現,有問題的大家可以給我留言