我需要上传图像并将其显示在浏览器的 Canvas 中。当我第一次上传此图像时, Canvas 宽度和高度为零,但第二次图像显示正确吗?为什么?
function previewFile() {
const canvas = document.getElementById('canvas');
const img = document.createElement('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
img.src = reader.result;
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="./script.js"></script>
<title>Document</title>
</head>
<body>
<input type="file" onchange="previewFile()"><br>
<canvas id="canvas"></canvas>
</body>
</html>
最佳答案
当您设置图像源时,它不会同步加载,因此您必须等待图像加载事件,然后才能将其绘制在 Canvas 上。
JS中很多与资源相关的操作都是异步的,所以你必须处理它。
function previewFile() {
const canvas = document.getElementById('canvas');
const img = document.createElement('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
img.src = reader.result;
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
}
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="./script.js"></script>
<title>Document</title>
</head>
<body>
<input type="file" onchange="previewFile()"><br>
<canvas id="canvas"></canvas>
</body>
</html>
关于javascript - 为什么我无法预览输入字段上传的图像并将其显示在 Canvas 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48687516/