html框架,包括css
通过 .container的样式将canvas影藏起来,从而实现在选择上传时默默缩小文件的大小,而不让用户察觉
canvas转化后的图片为base64格式,可转为file对象上传至服务器
Document.container{
width: 0;
height: 0;
overflow: hidden;
}
canvas {
border: 1px solid #000;
}
JavaScript,可将下面代码放到body中,也可放在单独的js文件中,然后在body引入
var from = document.querySelector('#btn')
from.onchange = function (e) {
var imgurl = window.URL.createObjectURL(from.files[0])
console.log(imgurl)
var image = new Image()
image.onload = function () {
var myCanvas = document.querySelector('canvas')
var ctx = myCanvas.getContext('2d')
var imageWidth = image.width
var imageHeight = image.height
//定义压缩后的宽度,也可封装后调用时传入
var img_width = 750 //此处的750是压缩后图片的宽度,也是canvas画布的宽度
//宽度750 ,通过计算可得出缩放后的高
myCanvas.height = img_width*imageHeight/imageWidth
myCanvas.width = img_width
ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, img_width,img_width*imageHeight/imageWidth)
var imageData = new Image();
// canvas.toDataURL 返回的是一串Base64编码的URL
// 指定格式 PNG
imageData.src = myCanvas.toDataURL("image/png");
}
image.src = imgurl
}
Canvas保存为图片到本地,可以将代码粘贴到方法中,通过点击事件执行
//myCanvas是html中的canvas标签对象,可通过 document.querySelector('xxx')获取
var bloburl = myCanvas.toDataURL();
console.log('bloburl', bloburl);
var anchor = document.createElement('a');
if ('download' in anchor) {
anchor.style.visibility = 'hidden';
anchor.href = bloburl;
anchor.download = name;
document.body.appendChild(anchor);
var evt = document.createEvent('MouseEvents');
evt.initEvent('click', true, true);
anchor.dispatchEvent(evt);
document.body.removeChild(anchor);
} else {
location.href = bloburl;
}
base64图片转file对象
//将base64转换为blob
dataURLtoBlob: function(dataurl) {
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 Blob([u8arr], { type: mime });
},
//将blob转换为file
blobToFile: function(theBlob, fileName){
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
},
//调用
var blob = dataURLtoBlob(bloburl);
var file = blobToFile(blob, imgName);