javascript
<!DOCTYPE html>
<html lang="CH-EN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>生成图片</title>
</head>
<body>
<div class="content">
<input type="file" name="file" id="file" />
<img src="" class="img" alt="图片" />
</div>
</body>
</html>
<script>
const file = document.querySelector("#file");
const img = document.querySelector("img");
// 添加监听内容变化时读取文件
file.addEventListener("change", () => {
// 实例化了一个reader对象
let reader = new FileReader();
// 当这个文件的内容读取完毕之后, 会把内容存放到 result里面,并调用load方法
reader.addEventListener("load", () => {
img.src = reader.result;
});
// 读取文件
reader.readAsDataURL(file.files[0]);
});
</script>
<style>
* {
font-size: 12px;
margin: 0;
padding: 0;
}
.content {
margin: 20px;
height: 500px;
border: solid #dddd 1px;
display: flex;
flex-direction: column;
align-items: center;
}
.content input {
margin-top: 10px;
}
.img {
margin-top: 10px;
height: 300px;
}
</style>
效果