https://zhuanlan.zhihu.com/p/27823933
或者
canvas.getContext(‘2d’).drawImage(img, dx, dy, dWidth, dHeight)
img 图片对象
dx 将图片画到canvas上时图片左上角在画布上的x坐标
dy 将图片画到canvas上时图片左上角在画布上的y坐标
dWidth 将图片画到canvas上时图片要画的宽度
dHeight 将图片画到canvas上时图片要画的高度
实现流程
用户点击input[file]选择图片后的逻辑
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<input type="file" accept="image/*" onchange="uploadImageHandle(event)" />
<script type="text/javascript">
function uploadImageHandle(e) {
// 创建实例
var reader = new FileReader(),
img = document.createElement('img');
// 读取上传的图片的信息(lastModified, lastModifiedDate, name, size, type等)
var file = e.target.files[0];
// 记下上传的图片的类型, 后面会用到
var fileType = file.type;
// 生成canvas画布
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
// MDN: 该方法会读取指定的 Blob 或 File 对象。读取操作完成的时候,
// readyState 会变成已完成(DONE),并触发 loadend 事件,
// 同时 result 属性将包含一个data:URL格式的字符串(base64编码)以表示所读取文件的内容。
// 也就是说, 将File对象转化为base64位字符串
reader.readAsDataURL(file);
// 上一步是异步操作, 读取完成后会执行onload事件, 而base64的字符串在e.target.rusult中
reader.onload = function(e) {
// 获得图片dom
img.src = e.target.result;
console.log(img);
};
img.onload = function() {
console.log(11111111111)
// 图片原始尺寸
var originWidth = this.width;
var originHeight = this.height;
// 最大尺寸限制
var maxWidth = 800,
maxHeight = 800;
// 目标尺寸
var targetWidth = originWidth,
targetHeight = originHeight;
// 图片尺寸超过800x800的限制
if(originWidth > maxWidth || originHeight > maxHeight) {
if(originWidth / originHeight > maxWidth / maxHeight) {
// 更宽,按照宽度限定尺寸
targetWidth = maxWidth;
targetHeight = Math.round(
maxWidth * (originHeight / originWidth)
);
} else {
targetHeight = maxHeight;
targetWidth = Math.round(
maxHeight * (originWidth / originHeight)
);
}
}
// canvas对图片进行缩放
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect(0, 0, targetWidth, targetHeight);
// 将图片划到canvas上
context.drawImage(img, 0, 0, 800, 800);
// 把canvas转成base64格式并去除头
var base64 = canvas
.toDataURL(fileType)
.replace(/^data:image\/(jpeg|jpg|png|gif);base64,/, '');
console.log(base64)
// 上传base64, 如果需要上传图片只需要参照上面的操作, 重复将base64设置为图片上的src就行了. 当然, 需要在去处头之前
// axios.post('https://yourdomain.com/api/xxx', {
// imageSrc: base64
// }).then(res => {
// console.log(res)
// }).catch(err => {
// console.log(err)
// })
};
}
</script>
</body>
</html>