Reputation: 2017
I have this code (stolen from the web):
function readIt() {
var reader = new FileReader();
reader.onload = (function(e) {
var img = new Image();
img.src = e.target.result;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.drawImage(img, 0, 0);
}
);
reader.readAsDataURL(document.getElementById('userImage').files[0]);
}
Which works up to a point. The canvas's width and height are set to the size of the image, but only the top left of the image appears - It appears to be stretched so it fits all the space allocated to the canvas (enough to display the whole image - 615px x 615px).
If I add an <img> element sized the same size as the canvas and point the src to the image in the file system it appears perfect.
I'm using Chrome, but it appears the same in Firefox.
Thanks in advance.
Upvotes: 0
Views: 88
Reputation: 105015
Several thoughts:
Here's some sample code:
var img=new Image();
img.onload=function(){
var c=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// resize the canvas element to the same size as the image
// DON'T RESIZE WITH CSS -- your results will appear stretched
c.width=img.width;
c.height=img.height;
// draw the image onto the canvas
ctx.drawImage(img,0,0);
}
img.src=e.target.result;
Upvotes: 1