//imgBase64:上传的图片的base64; rotate:上传的图片的翻转角度 function clearCanvas() { var c=document.getElementById("shwoCanvas"); if(!c.getContext){ return; } var cxt=c.getContext("2d"); c.height=c.height; $("#shwo").removeAttr("style"); $("#shwo").removeAttr("width"); } //上传的图片如果不是水平的,就翻转图片,获取翻转后图片的base64 function initCanvas(src, edg, localeArr ) { var canvas = document.createElement("canvas"); if(!canvas.getContext){ return; } var ctx = canvas.getContext("2d"); var imgW;//图片宽度 var imgH;//图片高度 var size;//canvas初始大小 edg = 360 - edg; if (edg % 90 != 0) { console.error("旋转角度必须是90的倍数!"); throw '旋转角度必须是90的倍数!'; } (edg < 0) && (edg = (edg % 360) + 360) const quadrant = (edg / 90) % 4; //旋转象限 const cutCoor = {sx: 0, sy: 0, ex: 0, ey: 0}; //裁剪坐标 var image = new Image(); image.crossOrigin = "anonymous" image.src = src; image.onload = function () { imgW = image.width; imgH = image.height; size = imgW > imgH ? imgW : imgH; canvas.width = size * 2; canvas.height = size * 2; switch (quadrant) { case 0: cutCoor.sx = size; cutCoor.sy = size; cutCoor.ex = size + imgW; cutCoor.ey = size + imgH; break; case 1: cutCoor.sx = size - imgH; cutCoor.sy = size; cutCoor.ex = size; cutCoor.ey = size + imgW; break; case 2: cutCoor.sx = size - imgW; cutCoor.sy = size - imgH; cutCoor.ex = size; cutCoor.ey = size; break; case 3: cutCoor.sx = size; cutCoor.sy = size - imgW; cutCoor.ex = size + imgH; cutCoor.ey = size + imgW; break; } if(quadrant != 0){//如果是0,就不用翻转图片 ctx.translate(size, size); ctx.rotate(edg * Math.PI / 180); ctx.drawImage(image, 0, 0); var imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey); if (quadrant % 2 == 0) { canvas.width = imgW; canvas.height = imgH; } else { canvas.width = imgH; canvas.height = imgW; } ctx.putImageData(imgData, 0, 0); var base64 = canvas.toDataURL(); $("#shwo").attr("src", base64); }else{ canvas.width = imgW; canvas.height = imgH; } initShwoCanvas(canvas.width, canvas.height, localeArr); }; } //画红框的canvas:shwoCanvas,适配长宽;最大宽度900,高度固定430 function initShwoCanvas(width, height, localeArr) { var newWH =resize_im(width, height, 430, 900); // jche 图像有缩放 var newW = newWH[0]; var newH = newWH[1]; var widthRate = newWH[2]; var heightRate = newWH[3]; jQuery("#shwoCanvas" ).attr('width',newW); jQuery("#shwoCanvas" ).attr('height',newH); $("#shwo").width(newW); drawRbox(localeArr, "shwoCanvas"); } var width_f = 1; var height_f = 1; function resize_im(w,h, canvasHeight, maxWidth){ height_f=parseFloat(canvasHeight)/ h ; width_f=height_f; if(w * width_f > maxWidth) { width_f = parseFloat(maxWidth) / (w ); } var newW = parseInt(w*width_f); var newH = parseInt(h*height_f); img_rate = height_f; return [newW, newH, width_f, height_f]; } function drawRbox(imgBoxes,canvasId){ /*canvas上绘制倾斜矩形 */ var canvas = document.getElementById(canvasId); if(canvas.getContext){ var ctx = canvas.getContext("2d"); ctx.strokeStyle = 'rgba(255,0,0,0.5)'; ctx.lineWidth = 1; ctx.clearRect(0,0,canvas.width,canvas.height); ctx.beginPath(); for(var i=0;i