• gulp填坑记(二)——gulp多张图片自动合成雪碧图


    为优化图片,减少请求会把拿到切好的图标图片,通过ps(或者其他工具)把图片合并到一张图里面,再通过css定位把对于的样式写出来引用的html里面,对于一些图片较多的项目,这个过程可能要花费我们一天的时间,来实现这步。今天这一步缩短到几秒钟就能完成,究竟是什么工具这么神奇呢,他就是gulp的一个插件gulp.spritesmith。下面一张图来说明他能做什么。

                                                                                                            

    第一步:npm install --save-dev gulp.spritesmith 安装 gulp.spritesmith

    第二部:配置gulpfile.js

    //引入gulp模块
    const gulp=require('gulp');
    
    //引入雪碧图合成插件
    const spritesmith=require('gulp.spritesmith');
    gulp.task('spritesmith',function(){
    	gulp.src('src/images/*.png')
    		.pipe(spritesmith({
    			imgName:'sprite.png',//保存合并后的名称
    			cssName:'dest/css/sprite.css',//保存合并后css样式的地址
    			padding:15,//合并时两个图片的间距
    			algorithm:'binary-tree',//注释1
    			//cssTemplate:'dest/css/handlebarsStr.css'//注释2
    			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;"+""+sprite.px.width+";"+
                         "height:"+sprite.px.height+";"+"} ");   }); return arr.join(""); } })) .pipe(gulp.dest('dest/images')); })

      

    注释一:

    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}};
         {{px.width}};
        height: {{px.height}};
    }
    {{/sprites}}
    

      需要要合成的图片:

      

      合成成功:

      

  • 相关阅读:
    27、springboot整合RabbitMQ(1)
    26、springboot与消息
    25、springboot与缓存整合Redis
    24、springboot与缓存(2)
    linux之参数实用讲解
    linux之创建临时文件的方法
    【转】linux之shfit
    linux之stat
    Shell 环境中的输入输出重定向
    Linux下samba的安装与配置
  • 原文地址:https://www.cnblogs.com/yanxinhua/p/6816141.html
Copyright © 2020-2023  润新知