基于cropper实现上传图片裁剪功能,保存原始图片尺寸分辨率,具体代码如下:
<!DOCTYPE html> <html> <head> <meta charset='UTF-8' /> <meta name="viewport" content="initial-scale=1, width=device-width, maximum-scale=1, user-scalable=no"> <meta name="wap-font-scale" content="no"> <meta name="format-detection" content="telephone=no" /> <title>66</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script> <link rel="stylesheet" href="item_content.css?16"> <link href="https://cdn.bootcss.com/cropper/3.1.3/cropper.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/cropper/3.1.3/cropper.min.js"></script> </head> <body> <div class="button2" style="left: 1rem!important;"> <button type="button" class="replace" onclick="document.getElementById('file').click()">替换封面</button> <input type="file" name="file" id="file" accept="image/*" style="display:none;"> </div> <!-- 蒙层 --> <div id="mask3" style="background-color:#000000;display: none;"></div> <!-- 模态框 --> <div id="model3" style="display: none;"> <img src="" alt="" id="photo" style="width: 100%;height: auto;"> <button style="position: absolute;left: 20%;width:6rem;height: 2.4rem;bottom: 5rem;border-radius:5px;border:0; font-size:1.2rem; color:#fff; background:#3eb5f3" id="clipImg">确定</button> <button style="position: absolute;right: 20%;width:6rem;height: 2.4rem;bottom: 5rem;border-radius:5px;border:0;background-color: #ffffff; color:#333;font-size:1.2rem" onclick="cancel_model3()">取消</button> </div> <script type="text/javascript"> function cancel_model3(){ $('#mask3').css("display",'none'); $('#model3').css("display",'none'); } $("#clipImg").on("click", function(){ var cas=$("#photo").cropper('getCroppedCanvas'); var base64url=cas.toDataURL('image/jpeg'); console.log(base64url); //生成base64图片的格式 }); </script> <script> function submitMessage(){ $('#mask').css("display",'none') $('#model').css("display",'none') } function replaceBackground(){ $('#mask2').css("display",'block'); $('#model2').css("display",'block'); } document.querySelector('#file').addEventListener('change', function(e) { var file = this.files[0]; if(file.type.indexOf("image") == 0) { var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { // 图片base64化 var newUrl = this.result; //console.log(newUrl) $("#cover_img").attr("src", newUrl); $('#mask3').css("display",'block'); $('#model3').css("display",'block'); var options = { aspectRatio: 350 / 350, dragMode: 'move', viewMode: 1, cropBoxResizable: false, preview: '.img-preview', } $("#photo") .cropper('destroy') // 销毁旧的裁剪区域 .attr('src', newUrl) // 重新设置图片路径 .cropper(options) // 重新初始化裁剪区域 }; } }, false); </script> </body> </html>
效果展示:
文章评论(0)