1、图片转换base64
function getImgToBase64(url,callback){//将图片转换为Base64 var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); var dataURL = canvas.toDataURL('image/png'); callback(dataURL); canvas = null; }; img.src = url; }
2、base64转换成file object
function dataURLtoFile(dataurl, filename) {//将base64转换为文件 var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, {type:mime}); } //可以将图片转换为base64 getImgToBase64('img/test.png',function(data){ var myFile = dataURLtoFile(data,'testimgtestimgtestimg'); console.log(myFile); });
3、base64绘制到canvas上面
<canvas id="myCanvas" width="800" height="800"></canvas> <script> var img = new Image(); img.src=imgbase64; let myCanvas =$("#myCanvas").get(0); myCanvas.getContext('2d').drawImage(img,0,0); myCanvas.getContext('2d').fillText("32中文132",50,50); </script>
裁剪图片:
<script> var t = this; $(function(){ $("#crop_img").click(function(){ t.editPic = document.getElementById('edit_pic'); // let cord = document.getElementById("x_y").value; let x11=cord.split(",")[0]; let y11=cord.split(",")[1]; let x22=cord.split(",")[2]; let y22=cord.split(",")[3]; t.editPic.height = y22-y11; t.editPic.width = x22-x11; var ctx = t.editPic.getContext('2d'); var images = new Image(); images.src = document.getElementById('show_img').src; images.onload = function(){ ctx.drawImage(images, x11, y11, x22-x11, y22-y11, 0, 0, x22-x11, y22-y11,); document.getElementById('show_crop').src = t.editPic.toDataURL("image/jpeg"); }; }); }); </script> <body> <img id="show_img" src=""><br /> <canvas id="edit_pic"></canvas> <input type="text" name="coor" placeholder="坐标" readonly="true" id="x_y" style="width: 600px"><br> <img id="show_crop" src=""><br /> </body>