相关技术文档
完整示例代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="file" id="file_btn">
<canvas id="canvas" style="border:1px solid #c3c3c3;"></canvas>
<script>
let file_btn = document.getElementById('file_btn');
let canvas = document.getElementById('canvas');
canvas.width = 540;
canvas.height = 420;
file_btn.addEventListener("change", function () {
let data_url = file_btn.files[0];
console.log(data_url);
let reader = new FileReader();
reader.readAsDataURL(data_url);
reader.onload = function () {
let cxt = canvas.getContext('2d');
let img = new Image();
img.src = this.result;
img.onload = function () {
cxt.clearRect(0,0,canvas.width,canvas.height);
let width = img.width;
let height = img.height;
let result = geometric_scaling(width,height,canvas.width,canvas.height);
if (result['scale_by']==='none'){
cxt.drawImage(img, (canvas.width-result['width'])/2, (canvas.height-result['height'])/2,result['width'],result['height'])
}
if (result['scale_by']==='width'){
cxt.drawImage(img, 0, (canvas.height-result['height'])/2,result['width'],result['height'])
}
if (result['scale_by']==='height'){
cxt.drawImage(img, (canvas.width-result['width'])/2, 0,result['width'],result['height'])
}
}
}
});
function geometric_scaling(image_width, image_height, canvas_width, canvas_height) {
let width = image_width;
let height = image_height;
let scale = 1;
let scale_by = 'none';
let return_data = {
width,height,scale,scale_by};
if (image_height < canvas_height && image_width < canvas_width){
return return_data
}
else if (image_height > canvas_height && image_width > canvas_width){
let scale_height = canvas_height / image_height;
let scale_width = canvas_width / image_width;
if (scale_height<scale_width){
scale = scale_height;
scale_by = 'height';
}
else {
scale = scale_width;
scale_by = 'width';
}
}
else if (image_height > canvas_height) {
scale = canvas_height / image_height;
scale_by = 'height';
}
else{
scale = canvas_width / image_width;
scale_by = 'width';
}
return_data['width'] = image_width * scale;
return_data['height'] = image_height * scale;
return_data['scale'] = scale;
return_data['scale_by'] = scale_by;
return return_data
}
</script>
</body>
</html>