优化代码

This commit is contained in:
wuxw 2024-09-24 15:28:19 +08:00
parent 2f898ef12d
commit 6788f372ac

View File

@ -23,18 +23,18 @@ export function translate(that, imgSrc, callback) {
export function translateH5(imgSrc, callback) { export function translateH5(imgSrc, callback) {
var img = new Image(); let img = new Image();
img.src = imgSrc; img.src = imgSrc;
img.onload = function () { img.onload = function () {
var that = this; let that = this;
var h = that.height; let h = that.height;
// 默认按比例压缩 // 默认按比例压缩
var w = that.width; let w = that.width;
if(h > 1080 || w > 1080){ if(h > 1080 || w > 1080){
let _rate = 0; let _rate = 0;
@ -49,32 +49,19 @@ export function translateH5(imgSrc, callback) {
} }
} }
var canvas = document.createElement('canvas'); let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
var ctx = canvas.getContext('2d'); let anw = document.createAttribute("width");
var anw = document.createAttribute("width");
anw.nodeValue = w; anw.nodeValue = w;
let anh = document.createAttribute("height");
var anh = document.createAttribute("height");
anh.nodeValue = h; anh.nodeValue = h;
canvas.setAttributeNode(anw); canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh); canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h); ctx.drawImage(that, 0, 0, w, h);
//压缩比例 //压缩比例
let quality = 0.3;
var quality = 0.3; let base64 = canvas.toDataURL('image/jpeg', quality);
var base64 = canvas.toDataURL('image/jpeg', quality);
canvas = null; canvas = null;
callback(base64); callback(base64);
} }
@ -101,14 +88,29 @@ function imageToBease64(that, imageUrl, callback) {
const canvas = res[0].node; const canvas = res[0].node;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
const image = canvas.createImage(); const image = canvas.createImage();
canvas.width = imgData.width;
canvas.height = imgData.height;
image.src = imgData.path; image.src = imgData.path;
image.onload = function() { image.onload = function() {
const canvasWidth = imgData.width; // 获取图片宽度
const canvasHeight = imgData.height; // 获取图片高度 let h = imgData.height;
ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight); // 绘制图片 // 默认按比例压缩
let w = imgData.width;
if(h > 1080 || w > 1080){
let _rate = 0;
if(h > w){
_rate = h/1080;
h = 1080;
w = Math.floor(w/_rate);
}else{
_rate = w/1080;
w = 1080;
h = Math.floor(h/_rate);
}
}
canvas.width = w;
canvas.height = h;
ctx.drawImage(image, 0, 0, w, h); // 绘制图片
//压缩比例 //压缩比例
let quality = 0.3; let quality = 0.3;