Reputation: 433
I am using <input type='file' onchange="readURL(this)"/>
control to upload image to my web service. Here I am using canvas
to reduce image size. The code is working fine, but at first time when we try to upload image it sends blank image and at second attempt it sends first image. That means I need a event of canvas that tells me when image has been drawn on the canvas
function readURL(input) {
if (input.files && input.files[0]) {
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
var reader = new FileReader();
reader.onload = function (e) {
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj, 0, 0, 300, 275);
};
imageObj.src = e.target.result.toString();
$.ajax({
//My Web Service call code
});
}
reader.readAsDataURL(input.files[0]);
}
}
So question is Is there any event in HTML5 canvas which tells that image has been drawn?
Upvotes: 0
Views: 99
Reputation: 115940
You must move your $.ajax
call inside the onload
handler of the image:
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj, 0, 0, 300, 275);
$.ajax({
//My Web Service call code
});
};
imageObj.src = e.target.result.toString();
Your code as written was making the Ajax call before the image loaded, and the image wasn't being drawn to the canvas until the load happened.
Upvotes: 1
Reputation: 105015
Try using reader.onloadend
instead of reader.onload.
BTW in an unrelated matter, there is a new bug in Chrome that is tripped by using new Image().
You're good if you use the alternate: document.createElement("img")
instead.
Finally (not critical), since you're doing image files, you might look into the reader.readAsDataURL
option on FileReader.
Upvotes: 1