Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  72] [ 3]  / answers: 1 / hits: 90993  / 13 Years ago, thu, july 21, 2011, 12:00:00

I would like to draw an image opened with the HTML5 File API on a canvas.



In the handleFiles(e) method, I can access the File with e.target.files[0] but I can't draw that image directly using drawImage. How do I draw an image from the File API on HTML5 canvas?



Here is the code I have used:



<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8/>
<script>
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
}

function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.drawImage(e.target.files[0], 20,20);
alert('the image is drawn');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type=file id=input/>
<canvas width=400 height=300 id=canvas/>
</body>
</html>

More From » canvas

 Answers
26

You have a File instance which is not an image.


To get an image, use new Image(). The src needs to be an URL referencing to the selected File. You can use URL.createObjectURL to get an URL referencing to a Blob (a File is also a Blob): http://jsfiddle.net/t7mv6/86/.


var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function() {
ctx.drawImage(img, 20,20);
alert('the image is drawn');
}
img.src = URL.createObjectURL(e.target.files[0]);

Note: be sure to revoke the object url when you are done with it otherwise you'll leak memory. If you're not doing anything too crazy, you can just stick a URL.revokeObjectURL(img.src) in the img.onload function.


References:



[#91081] Tuesday, July 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dantel

Total Points: 7
Total Questions: 102
Total Answers: 97

Location: Saint Lucia
Member since Sat, Jun 6, 2020
4 Years ago
dantel questions
;