投稿 搜索

热搜词

热门文章

当前位置: 站长天下 / Html5 CSS3 / html5上传图片预览压缩代码
html5上传图片预览压缩代码
标签:

插件介绍

    这是一款html5基于canvas制作网格布局图片上传预览,带图片压缩显示功能代码。

    浏览器兼容性

    浏览器兼容性
    时间:2018-05-22
    阅读:

html5上传图片预览压缩代码

简要教程

这是一款html5基于canvas制作网格布局图片上传预览,带图片压缩显示功能代码。

使用方法

在页面引入以下jquery.min.js文件

<script src="js/jquery.min.js"></script>
<script>
  (function ($) {
    $.extend({
      //压缩图片,参数1:file对象,参数2:压缩比例
      compress(file,scale) {
        return new Promise(function (resolve,reject) {
          let _scale=scale || 1;
          let cvs = document.createElement('canvas');
          let ctx = cvs.getContext('2d');
          let img = new window.Image();
          let imgType=file.type;
          img.src = URL.createObjectURL(file);
          img.onload=function () {
            cvs.width = img.width*_scale;
            cvs.height = img.height*_scale;
            ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
            resolve(cvs.toDataURL(imgType));
          }
        });
      }
    });
    $.fn.extend({
  
      //复制节点
      cloneNode(num){
        let p=this.parent();
        for (let i=0;i<num;i++){
          p.append(this.clone(true))
        }
      }
    });
    $(function () {
      $('li').cloneNode(6);//复制66个节点
      //点击触发input
      $('li').each(function (i) {
        $(this).click(function () {
          $('input').attr("name",'input_'+i).click();
        })
      });
  
      $("input").change(function () {
        let files=$(this)[0].files[0];//获取files对象
        let index=parseInt(($(this).attr('name')).split("_")[1]);
         //0.5为当前压缩比
        $.compress(files,0.5).then((url)=>{
          $('li').eq(index).css({"background-image": "url("+url+")"});
          //上传到服务器
          $.post('url',{base64:url},()=>{
              
          })
        })
      })
    })
  })(jQuery)
</script>

CSS样式

<style>
*{
    padding: 0;
    margin: 0;
}
ul{
    width: 1200px;
    margin: 30px auto;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
}
ul li{
    background: #00a2d4;
    list-style: none;
    flex-grow:10;
    width: 300px;
    height: 300px;
    margin-right: 20px;
    margin-bottom: 20px;
    border: 1px solid #f2f2f2;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    background-repeat: no-repeat;
    background-size: cover;
    box-sizing: border-box;
}
</style>