【问题标题】:How to draw image to canvas using input tag?如何使用输入标签将图像绘制到画布?
【发布时间】:2019-09-23 03:05:03
【问题描述】:

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

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

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

    您必须监听输入元素的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

    您可以阅读更多关于它的信息here

    这是一个有效的 jsfiddle:https://jsfiddle.net/xrqu2wfc/

    【讨论】:

      【解决方案2】:

      尝试:

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

      【讨论】:

        猜你喜欢
        • 2013-11-01
        • 1970-01-01
        • 2012-11-09
        • 1970-01-01
        • 1970-01-01
        • 2014-09-03
        • 1970-01-01
        • 2013-01-29
        • 2023-03-11
        相关资源
        最近更新 更多