The idea is: you have a file field, which is hidden, and an image. You use the image to show the select file dialog. Then I display the image in the canvas.
<input id="ytfile-select" type="hidden" value="" name="Foto[image]" />
<input style="display:none" id="file-select" accept="image/*"
name="Foto[image]" type="file" />
<img id="upload-image" src="/images/design/upload-image.png"
alt="upload-image-button" />
<canvas id="canvas">
Sorry, your browser doesn't support the <canvas> element.
</canvas>
$('#upload-image').click(function(){
$('#file-select').click();
});
$('#file-select').bind('change',function(){
var fileList = this.files;
var img = document.createElement("img");
img.classList.add("obj");
img.src = window.URL.createObjectURL(fileList[0]);
var ctx = document.getElementById('canvas').getContext("2d");
ctx.drawImage(img,0,0);
});
On Firefox 10, ctx.drawImage(img,0,0); only works when I have the Firebug debugger nad breakpoint on that line. Without the breakpoint, it doesn’t work. I checked it on another clean profile.
On Chrome, $('#file-select').click(); doesn’t open the file dialog.
Edit: this question has been already answered. However, I have no idea what the issue with Firefox is. Any ideas?
I used these websites to create this code:
- https://developer.mozilla.org/en/using_files_from_web_applications
- http://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
Edit 2:
I resolved the issue with the Firefox by doing this:
Behind the line var fileList = this.files;, I put:
reader = new FileReader();
reader.onload = function (event) {
$('#display').append('<img src ="' + event.target.result + '">');
};
reader.readAsDataURL(fileList[0]);
This will trigger the
clickevent:$('#file-select').trigger("click");Example:
JSFiddle demo: http://jsfiddle.net/t7P3v/
Update:
Indeed, if the
input type="file"isdisplay:noneit will not pop up. Still you can make it invisible to the user by some CSS:position:absolute; top:-999px; left:-999px