【问题标题】:How to display a picture from file input to canvas如何从文件输入显示图片到画布
【发布时间】:2020-11-18 22:31:45
【问题描述】:

我有以下代码:

index.html

<!DOCTYPE html>
<html>
<head>
<!-- meta, title, etc -->
</head>
<body>
<input type="file" accept="image/*" id="imgin" /> <br />
<canvas id="canvas"></canvas>
<script type="text/javascript" src="./scripts/main.js"></script>
</body>
</html>

main.js

const imgin = document.getElementById('imgin');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
imgin.addEventListener('change', drawimage);
function drawimage() {
//draw_image
}

现在,我想在画布被选中时在画布上绘制图像。 我该怎么做?

我发现所有图片都不是来自&lt;input&gt; 标签。

【问题讨论】:

标签: javascript html image file canvas


【解决方案1】:

const ctx = canvas.getContext('2d');
imgin.onchange = e => {
    const file = imgin.files[0];
    if(file) {
      const reader = new FileReader();
        reader.onload = () => {
            const img = new Image();
            img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0, img.width, img.height);
      }
            img.src = reader.result;
        };
        reader.readAsDataURL(file);
    }
}
<input type="file" accept="image/*" id="imgin" /> <br />
<canvas id="canvas"></canvas>

【讨论】:

    【解决方案2】:

    这里是 jsfiddle:click

    使用的 HTML:

    <input type="file" id="input"/>
    <canvas width="400" height="300" id="canvas"/>
    

    用过的JS:

    var input = document.getElementById('input');
    input.addEventListener('change', handleFiles);
    
    function handleFiles(e) {
        var ctx = document.getElementById('canvas').getContext('2d');
        var img = new Image;
        img.src = URL.createObjectURL(e.target.files[0]);
        img.onload = function() {
            ctx.drawImage(img, 0, 0, 400, 300);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2021-05-29
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2020-04-29
      • 2012-12-15
      相关资源
      最近更新 更多