简体   繁体   English

如何使用输入标签将图像绘制到 canvas?

[英]How to draw image to canvas using input tag?

i want to make image preview using canvas, and image should be preview after i upload it with input tag我想使用 canvas 进行图像预览,并且在我使用输入标签上传后图像应该是预览

i have try using img tag and make img src for canvas using img tag, i also try using onclick function but that does not work我尝试使用 img 标签并使用 img 标签为 canvas 制作 img src,我也尝试使用 onclick function 但这不起作用

HTML HTML

<canvas id="canvasImg"></canvas>
<input type="file" id="fileInp">

JS 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;

You have to listen to the onChange event of the input element otherwise your code will only trigger on load and never again.您必须聆听输入元素的onChange事件,否则您的代码只会在加载时触发,而不会再次触发。

<canvas id="canvasImg"></canvas>
<input type="file" id="fileInp" onchange="readImage(this)">

And then create the function:然后创建 function:

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;
}

I'm using window.URL.createObjectURL(input.files[0]);我正在使用window.URL.createObjectURL(input.files[0]); instead of your input.value .而不是你的input.value

You can read more about it here你可以在这里阅读更多关于它的信息

Here is a working jsfiddle: https://jsfiddle.net/xrqu2wfc/这是一个有效的jsfiddle: https://jsfiddle.net/xrqu2wfc/

try:尝试:

imgSrc = URL.createObjectURL(e.target.files[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM