HTML5 - drag&drop a JPG and receive its width - javascript

I want to receive the width of a JPG after dragging it into the browser window. The strange thing is, sometimes it works perfectly and sometimes a width of zero is returned.
fiddle
document.body.addEventListener('drop', function ( e )
{
e.stopPropagation();
e.preventDefault();
file = e.dataTransfer.files[0];
reader.readAsDataURL( file );
reader.onloadend = function()
{
var source = this.result;
var currentImg = new Image();
currentImg.src = source;
var someDiv = document.createElement("div");
someDiv.innerHTML = '<li>'+currentImg.width+'</li>';
document.getElementById("logs").appendChild(someDiv);
}
});

This happens because you probably get width before the image is loaded.
Put some code like this and you works correctly.
...
var currentImg = new Image();
currentImg.onload = function() {
var someDiv = document.createElement("div");
someDiv.innerHTML = '<li>'+currentImg.width+'</li>';
document.getElementById("logs").appendChild(someDiv);
}
currentImg.src = source;
...
put the onload before setting the sorce because onload is a callback function.

Related

Create one image in javascript

I have the following code to create an image with JavaScipt, the image appear on a button click. The problem is when the image is created and i click again the button another one appear, and i don't want that.
How i can solve that?
var img = new Image();
var div = document.getElementById('Table');
img.onload = function() {
div.appendChild(img);
};
img.src = 'Images/Email.png';
You could use a flag, which indicate when the image has been created, loaded and added to your DOM:
var div = document.getElementById('Table');
var hasImage = false; // flag
var button = document.getElementById('button');
button.addEventListener('click', function(event){
createImage();
});
var createImage = function(){
if(!hasImage) {
var img = new Image();
img.src = 'http://pipsum.com/435x310.jpg';
img.onload = function() {
div.appendChild(img);
hasImage = true;
};
}else{
console.log('image is already present');
}
};
<button id="button" type="button">Click Me!</button>
<div id="Table"></div >
Check if the image is already added to the DOM. If not, do so. If already added, only update the source.
It could be something like this:
var img = new Image();
var div = document.getElementById('Table');
var appended = false;
function appendImage() {
appended = true;
div.appendChild(img);
img.removeEventListener('load', appendImage);
}
function onClick() {
if (!appended) {
img.addEventListener('load', appendImage);
}
img.src = 'Images/Email.png';
}

Adding delete button for each image thumbnail preview

I want to put next to each thumbnail a little cross to be able to remove them one by one. I am able to remove image by click on it but I would like to have seperate button "x" to remove it.
fileInput.addEventListener("change", function (e) {
var filesVAR = this.files;
showThumbnail(filesVAR);
}, false);
function showThumbnail(files) {
var file = files[0]
var image = document.createElement("img");
var thumbnail = document.getElementById("thumbnail");
image.file = file;
image.setAttribute('class', 'imgKLIK5');
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
};
}(image))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
image.onload = function () {
ctx.drawImage(image, 100, 100);
}
}
});
Here is my code in JFIDDLE
Can You help me out, please?
see this example with close button:http://jsfiddle.net/kevalbhatt18/r0taz01L/1/
$('div').on('click', '.closeDiv', function () {
$(this).prev().remove();
$(this).remove();
$('#upload-file').val("");
});
And I made this changes in your showThumbnail function
function showThumbnail(files) {
var file = files[0]
var thumbnail = document.getElementById("thumbnail");
var pDiv = document.createElement("div");
var image = document.createElement("img");
var div = document.createElement("div");
pDiv.setAttribute('class', 'pDiv');
thumbnail.appendChild(pDiv);
image.setAttribute('class', 'imgKLIK5');
pDiv.appendChild(image)
div.innerHTML = "X";
div.setAttribute('class', 'closeDiv');
pDiv.appendChild(div).......
...................
Just add new button element on each preview with following style attributes,
float:right;
position:relative;
you can remove the img from div thumbnail on click the "x" button, check this fiddle

Upload the same image file twice - Javascript

I have an image uploader in my drawing application that I've written in Javascript. I want to allow the user to place multiple of the same image on the canvas. However, when I try to upload an image that's already on the canvas, nothing happens and a breakpoint in my event handler for the uploader never gets hit. What's going on and how can I fix it? Thanks!
Here's the code for my image handler:
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function() {
img.className = 'drag';
img.style.left = 0;
img.style.top = 0;
context.drawImage(img, parseInt(img.style.left, 10) , parseInt(img.style.top, 10));
images.push(img);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
};
I do tend to agree with Rene Pot to use the same image again (duplicate button), but you still can't prevent the user from inserting/loading the same image again. I've encountered the problem a while ago and used this bit of code to check if the image is already cached (if cached, there is no load, hence the onload won't fire either).
var img = new Image();
img.src = event.target.result;
var insertImage = function() {
img.className = 'drag';
img.style.left = 0;
img.style.top = 0;
context.drawImage(img, parseInt(img.style.left, 10) , parseInt(img.style.top, 10));
images.push(img);
}
if(img.complete){
img.onload = insertImage;
} else {
insertImage();
}
Hope that helps.

<img>width returns 0 under heavy load

The below handleFiles method is being passed files from both drag and drop and a file input. After it gets the data url for a given file it passes it to the processImage function. This function creates a new image and sets the src and file for that image. I then take different actions based on the width of the incoming image and insert the image into the dom. However, I noticed when dropping in a bunch of images imageWidth will get set to 0. I have confirmed the image.src is correctly set and that dropping the same image in by itself works fine. I also have confirmed that if I remove the width calculations the image does display correctly on the page. When I enter the debugger I can confirm that immediately after imageWidth is set to 0 i.width returns a correct value. At first I thought it might be a threading issue in Chrome, but then when I saw it happen in FireFox as well I became alarmed. I have not been able to pinpoint a certain threshold, but the more load you put on the browser the less likely it is to correctly get the width.
I am seeing the problem in both FireFox 16.0.2 and Chrome 23.0.1271.95.
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
if( !isImage(file) ) {
continue;
}
var reader = new FileReader();
reader.onloadend = function(e) {
var dataURL = e.target.result;
processImage(file, dataURL);
}
reader.readAsDataURL(file);
}
}
function processImage(file, dataURL) {
var i = new Image();
i.src = dataURL;
i.file = file;
//console.log(i);
var maxWidth = 600;
var imageWidth = i.width;
......
}
As with all images, they may need time to load before they will tell you their width:
var i = new Image();
i.onload = function() {
//console.log(i);
var maxWidth = 600;
var imageWidth = this.width;
}
i.src = dataURL;
i.file = file;
The width (and height) might be 0 because it's not loaded yet.
Try adding the load event like so:
function processImage(file, dataURL) {
var i = new Image();
i.addEventListener("load", function () {
var maxWidth = 600;
var imageWidth = i.width;
......
});
i.src = dataURL;
i.file = file;
}

image,onload event not working in chrome

I'm using html5 to create drag and drop image upload functionality. This works great for me in firefox but in chrome the image onload event only fires the first time. If I drag multiple images in only the first works and if I drag a second in it fails. I believe the problem is with the image onload.
here is the way my code works I have removed the irrelevant sections:
var img = document.createElement("img");
var reader = new FileReader();
var canvas = document.createElement("canvas");
var canvasData;
var ctx = canvas.getContext("2d");
var myFiles;
var i = 0;
reader.onload = (function (aImg)
{
return function (e)
{
aImg.src = e.target.result;
};
})(img);
img.onload = function (){
//resizes image
//draws it to the canvas
//posts to server
i++;
if(i < myFiles.length){
processNext(i);
}
}
function processNext(filei) {
var file = myFiles[filei];
img.file = file;
reader.readAsDataURL(file);
}
i = 0;
myFiles = files;
processNext(0);
Does anyone know why this works in firefox but not chrome?
Explanation from chromium tracker:
This is not a bug. WebKit is just more strict. You must instantiate a new Image() object before the replacement, like this:
var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;
source: http://code.google.com/p/chromium/issues/detail?id=7731#c12
This is strange, none of the above worked for me. I was defining the image variable as local and change it to global and it started working. Does this make sense? Can somebody explain it?
This didnt worked for me:
function loadImage() {
var ImageToLoad = new Image();
ImageToLoad.onload = function() {
console.log("finish loading");
};
ImageToLoad.src = "myimage.png";
}
This did work:
var ImageToLoad = new Image();
function loadImage() {
ImageToLoad.onload = function() {
console.log("finish loading");
};
ImageToLoad.src = "myimage.png";
}

Categories

Resources