canvas上传图片base64-有裁剪功能-Jcrop.js

图片实例
1.初始样子
这里写图片描述
2.点击上传图片-弹出框
这里写图片描述
3.可以设置是否-上传图片大小,limitImg = true
这里写图片描述
4.可以设置是否-有裁剪图片大小条件,limitImg = true,可手动更改
这里写图片描述
5.裁剪过大图片,可以进行比例缩小,到你需要的尺寸。(eg:实际裁剪过大,自动生成1400px,可配置)
这里写图片描述
6.点击裁剪成功后canvas画图
var ctx = canvasNow.getContext(‘2d’);
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
这里写图片描述

部分代码实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
  <link rel="stylesheet" type="text/css" href="css/Jcrop.css">
  <link rel="stylesheet" type="text/css" href="css/jquery.Jcrop.min.css">
</head>
<body>
    <img class="upload-btn" width="135" src="css/default-thumbnail.png" alt="">
  <div class="head-img-modal">
    <div class="head-img-modal">
      <div class="img-upload-box">
        <div class="modal-title">
          <span>图片剪切</span>
          <img src="css/close-modal.png" class="close-modal">
        </div>
        <div class="img-edit-box">
            <label>
            <input type="file" name="" value="选择图片" class="file-hidden" onchange="showSelectedImages(this.files);" name="img" style="display:none">
            <a href="javascript:void(0);" class="file-faker btn btn-default btn-sm">选择图片</a>
          </label>
          <div class="cut-img-box clearfix">
            <div class="cut-box">
               <img src="javascript:void(0);" id="cut-img">
            </div>
            <div class="show-img-box" style="display:none">
              <div id="preview-pane">
                <div class="preview-container">
                  <img src="javascript:void(0);" id="show-img" class="jcrop-preview">
                </div>
              </div>
            </div>
          </div>
          <div class="cut-btn-box">
              <a href="javascript:void(0);" class="cut-btn btn btn-default btn-sm">确认裁剪</a>
          </div>
        </div>  
      </div>  
    </div>
  </div>  
  <canvas class="crop-canvas" style="display: none;"></canvas>
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script type="text/javascript" src="js/jquery.Jcrop.min.js"></script>
    <script type="text/javascript">
        $('.upload-btn').on('click', function () {
        $('.head-img-modal').show();
    });
    $('.file-faker').on('click', function () {
        $('.file-hidden').trigger('click');
    });
    // 关闭按钮
    $('.close-modal').on('click', function () {
        $('.head-img-modal').hide();
    })
    var jcrop_api;
    var limitW = 710,//上传图片最小宽度
        limitH = 710,//上传图片最小高度
        limitMaxW = 1420,//裁剪原图片最大宽度
        limitImg = true,//是否需要添加图片限制。
        imgW,//获取实际上传图片的尺寸 
        imgH;   
    function showSelectedImages(files) {
      createReader(files[0], function (w, h) { 
        imgW = w;
        imgH = h;
        // alert(w + ' '+ h);
        if (isImageByType(files[0].type)) {
          // 判断是否需要添加尺寸大小判断
          if(limitImg){
            // 判断上传图片尺寸
            if(imgW >= limitW && imgH >= limitH){
              var img = document.getElementById('cut-img');
              var newImg = document.getElementById('show-img');
              var jImg = document.querySelector('.jcrop-holder img');
              img.src = window.URL.createObjectURL(files[0]);
              newImg.src = window.URL.createObjectURL(files[0]);
              isShowImage(img);
            } else {
              alert('请上传大于710*710尺寸的图片');
            }
          }else{
            var img = document.getElementById('cut-img');
            var newImg = document.getElementById('show-img');
            var jImg = document.querySelector('.jcrop-holder img');
            img.src = window.URL.createObjectURL(files[0]);
            newImg.src = window.URL.createObjectURL(files[0]);
            isShowImage(img);
          }
        } else {
            alert('请上传图片');
        }
      });


    }
    createReader = function(file, whenReady) {
        var reader = new FileReader;
        reader.onload = function (evt) {
            var image = new Image();
            image.onload = function () {
                var width = this.width;
                var height = this.height;
                if (whenReady) whenReady(width, height);
            };
            image.src = evt.target.result;
        };
        reader.readAsDataURL(file);
    }
    // 判断上传的是否是图片类型
    function isImageByType(fileType) {
        return fileType.indexOf('image') < 0 ? false : true;
    }
    // 将图片展示出来在画布上
    function isShowImage(img) {
        if (jcrop_api) {
            jcrop_api.destroy();
            $('#cut-img').css({'width': 'auto', 'height': 'auto'});
            jcrop_api = null;
        };
        var boundx;
        var boundy;
        var $preview = $('#preview-pane');
        var $pcnt = $('#preview-pane .preview-container');
        var $pimg = $('#preview-pane .preview-container img');
        var xsize = $pcnt.width();
        $('#cut-img').Jcrop({
            bgOpacity: 0.5,
            bgColor: 'black',
            addClass: 'jcrop-dark',
            aspectRatio: 1,  //宽:高
            onChange: updatePreview,
            onSelect: updatePreview,
        }, function () {
            jcrop_api = this;
            jcrop_api.setSelect([50, 50, 50 + 150, 50 + 150]);
            jcrop_api.setOptions({
                bgFade: true
            });
            jcrop_api.ui.selection.addClass('jcrop-selection');
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
        });

        function updatePreview(c) {
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = xsize / c.h;

                $pimg.css({
                    width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
        }
    }
    // 确认裁剪
    $('.cut-btn').on('click', function () {
        var originalHeight = $('.jcrop-holder').height();
        var originalWidth = $('.jcrop-holder').width();
        var bili =  imgH/originalHeight;
        var canvasNow = $('.crop-canvas')[0];
        var canvasWidth = $('.jcrop-selection').width();
        var canvasHeight = $('.jcrop-selection').height();
        var leftNum = $('.jcrop-selection').css('left').split('px')[0] * 1.0;
        var topNum = $('.jcrop-selection').css('top').split('px')[0] * 1.0;

        canvasNow.width =  canvasWidth * bili;
        canvasNow.height = canvasHeight * bili;
        // 判断是否需要添加尺寸大小判断
        if(limitImg){
          if (canvasNow.width >= limitW * 2 && canvasNow.height >= limitH * 2) {
            var biliNOW = limitMaxW*bili/canvasNow.width;//获当图片大于1420,获取新的比例
            canvasNow.width =  limitMaxW;
            canvasNow.height = limitMaxW;
            var ctx = canvasNow.getContext('2d');
            ctx.clearRect(0, 0, canvasWidth, canvasHeight);
            ctx.drawImage($('#show-img')[0], -leftNum * biliNOW, -topNum * biliNOW, originalWidth * biliNOW, originalHeight * biliNOW);
            var imgData = canvasNow.toDataURL('image/jpeg');
          }else{
            var ctx = canvasNow.getContext('2d');
            ctx.clearRect(0, 0, canvasWidth, canvasHeight);
            ctx.drawImage($('#show-img')[0], -leftNum * bili, -topNum * bili, originalWidth * bili, originalHeight * bili);
            var imgData = canvasNow.toDataURL('image/jpeg');
          }

          console.log(imgData);

          // 判断裁剪图片尺寸
          if(canvasNow.width >= limitW && canvasNow.height >= limitH){
            $('.head-img-modal').hide();
            $('.upload-btn').attr('src',imgData);
            $('.cover_img').attr('value',imgData);
          }else{
            alert('裁剪图片尺寸需大于710x710px')
          } 
        }else{
          var ctx = canvasNow.getContext('2d');
          ctx.clearRect(0, 0, canvasWidth, canvasHeight);
          ctx.drawImage($('#show-img')[0], -leftNum * bili, -topNum * bili, originalWidth * bili, originalHeight * bili);
          var imgData = canvasNow.toDataURL('image/jpeg');
          $('.head-img-modal').hide();
          $('.upload-btn').attr('src',imgData);
          $('.cover_img').attr('value',imgData);
        }   
        // alert(imgW + ' '+ imgH);
    });
    </script>
</body>
</html>

具体代码下载地址:https://download.csdn.net/download/qq_29132907/10649161

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页