首页 > 解决方案 > 如何使用输入标签将图像绘制到画布?

问题描述

我想使用画布进行图像预览,并且在我使用输入标签上传图像后应该预览图像

我尝试使用 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;

标签: javascripthtmlhtml5-canvas

解决方案


您必须监听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/


推荐阅读