Reputation: 89
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.
Upvotes: 0
Views: 1778
Reputation: 1650
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>
Upvotes: 2
Reputation: 2713
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);
}
}
Upvotes: 4