jcanvas
官网:https://projects.calebevans.me/jcanvas/
中文翻译:http://asprain.cn/jCanvas/p843.htm
具体实现:
需要引入jcanvas.min.js,exif.js。 exif.js是修正图片带有exif的orientation信息的时候,在安卓上没办法正常显示的问题。
html:
<div class =“canvas-area”> <imgclass=“fakeimg”src=“2018/0115/c8f6c06398978870.png”alt =“”> <canvas class =”cv“> </ canvas> <input type =”file“class =”upload-file“style =”display:none;“> </ div>css:
.canvas-area { position: relative; width: 4.74rem; height: 4.74rem; overflow: hidden; border: solid 2px #000d41; } .canvas-area .fake-img { position: absolute; top: 0; left: 0; z-index: 2; width: 100%; height: 100%; } .cv{ width: 100%; height: 100%; }
js:
var $fileTag = $('.upload-file'), oCanvas = $('.cv'), oUploadBtn = $('.fake-img'); var c_width = oUploadBtn.width(), c_height = oUploadBtn.height(); var img_times = 1; var c_center = c_width; var _exifInfo = {}; //让图片高清显示 oCanvas.attr({'width':c_width*img_times,'height':c_width*img_times}); oUploadBtn.click(function () { g_upload_img(); }); /*图片上传*/ function g_upload_img() { $fileTag.click(); $fileTag[0].onchange = function () { var file = $fileTag[0].files[0]; var fileReader = new FileReader(); fileReader.onloadend = function () { if (fileReader.readyState == fileReader.DONE) { var aimg=new Image(); aimg.src = fileReader.result; $(aimg).load(function() { EXIF.getData(this, function(){ _exifInfo = EXIF.getAllTags(this); }); var _rotate = 0; var _DragToAxis = null; // exif.js修正图片带有exif的orientation信息的时候,在安卓上没办法正式显示的问题。假如图片是ios及数码相机拍摄,那么它就会带有exif信息,其中一个叫orientation的方向信息,这个方向是你拍摄的方向,假如有这个方向的话,在pc,安卓及ios上面的显示都不一样。 switch (_exifInfo.Orientation) { case 7: case 8: _rotate = -90; break; case 3: case 4: _rotate = 180; break; case 5: case 6: _rotate = 90; break; } var max_width,max_height; max_width = c_width > aimg.width ? aimg.width:c_width; max_height = c_height > aimg.height ? aimg.height:c_height; var c_width = oUploadBtn.width(), c_height = oUploadBtn.height(); //ratiow:上传的图片的宽度与canvas宽度的比例 //ratioh:上传的图片的高度与canvas高度的比例 //判断上传的图片的宽度和高度哪个大,哪个大就以这个大小作为画布的高度和宽度。上传的图片按照小的那边等比缩放,缩放到与框的宽度或高度相等。 var ratiow = aimg.width/c_width, ratioh = aimg.height/c_height; var c_h = c_height, c_w = c_width,ratioend=1; if(ratiow>ratioh) { c_height = ratiow*c_height; c_width = aimg.width; ratioend = ratiow; scale_c = 1/ratioh; } else{ c_width = ratioh*c_width; c_height = aimg.height; ratioend = ratioh; scale_c = 1/ratiow; } if(c_width<=c_w&&c_height<=c_h) { c_width = c_w; c_height = c_h; ratioend = 1; scale_c = 1; } oCanvas.attr({'width':c_width*1,'height':c_height*1}); // 永久删除图层 oCanvas.removeLayer('myBox').drawLayers(); oCanvas.clearCanvas().drawImage({ layer: true,//jCanvas绘制的东西是否应该加为一个图层 name: 'myBox',//关联到图层的名称 source: fileReader.result,//要绘制的图像的源 x: c_width/2,//一个形状在画布上的x位置 y: c_height/2,//一个形状在画布上的y位置 width: c_w*ratiow*ratioend,//形状的宽度 height: c_h*ratioh*ratioend,//形状的高度 draggable: true,//是否可拖曳 rotate: _rotate,//旋转的角度 scale: scale_c//画布的宽度和高度的倍数(用于缩放) }); }) } }; fileReader.readAsDataURL(file); }; }