0

I have following code:

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
}

Now, I want to draw the Image on canvas when it is choosed. How should I do so?

All I found were not putting image from <input> tag.

Croximo Crox
  • 79
  • 10
  • 2
    Does this answer your question? [How to upload image into HTML5 canvas](https://stackoverflow.com/questions/10906734/how-to-upload-image-into-html5-canvas) – Simone Rossaini Jul 29 '20 at 10:44

2 Answers2

4

Here is jsfiddle: click.

Used HTML:

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

Used 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);
    }
}
Anton
  • 2,669
  • 1
  • 7
  • 15
  • 1
    This is good answer. The `FileReader()` seems to be no need. However, the width and height can be set from image file with `img.width`, `img.height` instead of `400`, `300`. This is in case someone stuck with stretched image. Upvoted :) – vee Dec 03 '22 at 06:32
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>
Darth
  • 1,592
  • 10
  • 19