JavaScript 上传前的JavaScript图片预览
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 上传前的JavaScript图片预览相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html>
<head>
<title>JavaScript image preview before upload</title>
<script type="text/javascript">
var e = document.getElementById('cover');
e.onchange = function getPreview() {
var file = this.files[0];
resizeImage(file).then(function(cover) {
var cpreview = document.getElementById("preview-image");
cpreview.setAttribute('style', 'background-image: url(\'' + cover + '\'); background-size: contain;');
});
}
function resizeImage(file) {
return new Promise(function(a) {
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
var ready = false;
reader.onload = function(e) {
img.src = e.target.result;
img.onload = function() {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var width = img.width;
var height = img.height;
var canvasRatio = 0.75;
var ratio = img.height / img.width;
if (ratio < canvasRatio) {
img.width = width * 600 / height;
img.height = 600;
} else {
img.height = height * 800 / width;
img.width = 800;
}
canvas.width = 800;
canvas.height = 600;
ctx.drawImage(img,
400 - img.width / 2,
300 - img.height / 2,
img.width,
img.height
);
var dataurl = canvas.toDataURL('image/jpeg', 1.0);
ready = true;
a(dataurl);
}
}
reader.readAsDataURL(file);
})
}
</script>
</head>
<body>
<label for="cover">
<span>Upload game cover…</span>
<input type="file" id="cover" name="cover">
</label>
<div id="preview-image"></div>
</body>
</html>
以上是关于JavaScript 上传前的JavaScript图片预览的主要内容,如果未能解决你的问题,请参考以下文章