javascript - 如何使用输入标签将图像绘制到画布?
问题描述
我想使用画布进行图像预览,并且在我使用输入标签上传图像后应该预览图像
我尝试使用 img 标签并使用 img 标签为画布制作 img src,我也尝试使用 onclick 功能,但这不起作用
HTML
<canvas id="canvasImg"></canvas>
<input type="file" id="fileInp">
JS
const input = document.getElementById('fileInput');
const canvas = document.getElementById('canvasImg');
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
let imgSrc = '';
if (input.value !== ''){
imgSrc = input.value;
}
const img = new Image();
img.onload = function(){
context.drawImage(img, 0, 0);
}
img.src = imgSrc;
解决方案
您必须监听onChange
输入元素的事件,否则您的代码只会在加载时触发,而不会再次触发。
<canvas id="canvasImg"></canvas>
<input type="file" id="fileInp" onchange="readImage(this)">
然后创建函数:
function readImage(input) {
const canvas = document.getElementById('canvasImg');
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
let imgSrc = '';
if (input.value !== '') {
imgSrc = window.URL.createObjectURL(input.files[0]);
}
const img = new Image();
img.onload = function() {
context.drawImage(img, 0, 0);
}
img.src = imgSrc;
}
我正在使用window.URL.createObjectURL(input.files[0]);
而不是您的input.value
.
你可以在这里阅读更多关于它的信息
这是一个有效的 jsfiddle:https ://jsfiddle.net/xrqu2wfc/
推荐阅读
- javascript - 我正在编写一个弹出扩展程序,但我被困在设计中
- android - 如何在 webview Android 中处理多个窗口选项卡
- subshell - 在powershell中将当前工作目录传递给bash
- c# - 如何获取第二个逗号的索引?
- arangodb - ArangoDB 基于子属性的多个过滤器检索父对象
- android - Android SDK Sensoro 传感器服务不可用
- reactjs - React - 根据其他组件的位置渲染组件
- javascript - 播放或暂停音频时更改 innerHTML
- docker - db-migrate 在 docker deploy 找不到 heroku 配置变量
- c++ - 在 C++ 中修改常量向量