I have been working to change a github code to upload multiple images and get result.
https://github.com/giventofly/pixelit
Tried many ways. But not working.
document.addEventListener("DOMContentLoaded", function () {
//load image to canvas
document.getElementById("pixlInput").onchange = function (e) {
var img = new Image();
img.src = URL.createObjectURL(this.files[0]);
img.onload = () => {
//create element
//document.getElementById('teste').src = img.src;
px.setFromImgSource(img.src);
pixelit();
//.pixelate()
//.convertGrayscale()
//.convertPalette();
//.saveImage();
//console.log(px.getPalette());
};
};
This is the source code. Please help
Related
An overall explanation of my code is that I am making an animation. I have 3 canvases, one for the base image, one for the streamline wind map drawing, and the last one an image that is covering up part of the drawing. My code below shows the two images being uploaded..
var img = document.createElement("img");
var cvrimg = document.createElement("cvrimg");
img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";
cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";
img.crossOrigin = "anonymous"
cvrimg.crossOrigin = "anonymous"
img.onload = function () {
imgctx.drawImage(img, 10, 10);
cvrimg.onload = function () {
console.log("maybe");
cvrctx.drawImage(cvrimg,10,10);
startDrawing(wdDataArr,wsDataArr,dataManArr,pastDataArr,onlineArr);
}
}
I put some log statements in the code and the cvrimg.onload function is not being called. The network tab in the inspect tool on chrome only shows one image being queried.
Any advice is appreciated for this novice programmer.
Thank you.
You're defining the cvrimg.onload function only when img.onload is called. If cvrimg is loaded before img.onload is called, it wouldn't call the function, because it's simply not deifned.
Also, cvrimg = document.createElement("cvrimg") creates <cvrimg> element, which makes no sense.
Option 1 – parallel loading
let img = document.createElement("img"),
cvrimg = document.createElement("img");
img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";
cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";
img.onload = function() {
console.log("img loaded");
...
}
cvrimg.onload = function() {
console.log("cvrimg loaded");
...
}
Option 2 – serial loading
let img = document.createElement("img"),
cvrimg = document.createElement("img");
img.src = "https://cors-anywhere.herokuapp.com/www.example.com/img.png";
img.onload = function() {
console.log("img loaded, loading cvrimg now");
cvrimg.scr = "https://cors-anywhere.herokuapp.com/www.example.com/img-two.png";
...
}
cvrimg.onload = function() {
console.log("cvrimg loaded");
...
}
I'm trying to load an image on to a canvas so I can write some text on it and maybe save it later on. I have two below functions:
openImage = (memeURL, index) => {
this.setState({currentMeme: index}, () => {
const base_image = new Image();
base_image.crossOrigin = "anonymous";
base_image.src = memeURL;
const base64 = this.getBase64Image(base_image);
this.setState({currentImagebase64: base64});
})
}
getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
}
The openImage function is bound to an onClick event so when I click an image it fires up the above operations so that my <img src=""> can feed from state and display the image.
The problem is that when i click the image it never shows up and my currentImagebase64 state value is always data; BUT if debug with web tools it appears fine because theres enough time for the image to load. Aparrently the solution is in the below answer:
canvas.toDataUrl() returns 'data:,'
However, if I write something like suggested the onload function never triggers. For example below code won't trigger the onload for some reason, it just stops executing when it reaches it:
openImage = (memeURL, index) => {
this.setState({currentMeme: index}, () => {
const base_image = new Image();
base_image.onload = function() {
this.crossOrigin = "anonymous";
}
//Set src AFTER the image has loaded
base_image.src = memeURL;
const base64 = this.getBase64Image(base_image);
this.setState({currentImagebase64: base64});
})
}
Can any subject experts lend a hand please?
const base64 = this.getBase64Image(base_image);
this.setState({currentImagebase64: base64});
needs to be executed once the image has loaded
and
base_image.crossOrigin = "anonymous";
needs to be done before setting the src
So, the code becomes
openImage = (memeURL, index) => {
this.setState({currentMeme: index}, () => {
const base_image = new Image();
base_image.crossOrigin = "anonymous";
base_image.onload = () => { // use arrow function so `this` will be what is needed
const base64 = this.getBase64Image(base_image);
this.setState({currentImagebase64: base64});
}
base_image.src = memeURL;
})
}
Your comment
//Set src AFTER the image has loaded
suggests you don't know how onload works ... you set src which starts loading the image, and then onload is triggered when image finishes loading
I'm not entirely sure how react handles the states as above but I've had a similar issue in vanilla JS in which the src wasn't loading until added to the DOM. Keeping it hidden was fine though:
const image = new Image();
image.onload = (e)=>{
// do something
}
image.src = YOUR_IMAGE_PATH;
image.hidden = true;
// add to body
document.body.appendChild(image); // at this point the src is loaded and onload handler is fired
I am trying to load an image with an html input type="file" and load it to an with javascript without success.
Here is my code so far:
HTML:
<canvas class="imported" id="imported"></canvas>
<button class="import_button" id="import_button">Import a picture</button>
<input type="file" id="imgLoader"/>
JAVASCRIPT:
document.getElementById('import_button').onclick = function() {
document.getElementById('imgLoader').click();
};
document.getElementById('imgLoader').addEventListener('change', importPicture, false);
function importPicture()
{
alert("HERE");
var canvas = document.querySelector('#imported');
var context = canvas.getContext("2d");
var fileinput = document.getElementById('imgLoader');
var img = new Image();
var file = document.getElementById('imgLoader').files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt)
{
alert("THERE");
if( evt.target.readyState == FileReader.DONE)
{
alert("AGAIN");
img.src = evt.target.result;
context.drawImage(img, 200, 200);
}
}
}
The alerts are all fired up, no errors or message in the console..
How can I load it and display it? Thank you!
The logic (of your original code, not the edited version) is a bit baffling:
document.getElementById('imgLoader').addEventListener('change', importPicture, false);
adds a change event to the file input. That's fine. But then within the "importPicture" function, which runs when the file input changes, you add another change event listener (via fileinput.onchange) ...why are you doing that? I can't see how it makes sense. It means you have to change the file again before the code in there runs. And it also means that every time you change the file it adds more and more listeners, until you have lots of functions firing at once.
The other problem is that you're not waiting for the data to be loaded into the Image object before you try to draw the image on the canvas. You also need to set the dimensions of the canvas itself, and not be prescriptive about the dimensions of the image (because the user could upload anything, of any size).
Here's a working demo:
document.getElementById('import_button').onclick = function() {
document.getElementById('imgLoader').click();
};
var fileinput = document.getElementById('imgLoader').addEventListener('change', importPicture, false);
function importPicture() {
var canvas = document.querySelector('#imported');
var context = canvas.getContext("2d");
var img = new Image();
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(evt) {
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0);
}
img.src = evt.target.result;
}
reader.readAsDataURL(file);
}
<canvas class="imported" id="imported"></canvas>
<button class="import_button" id="import_button">Import a picture</button>
<input type="file" id="imgLoader" />
Credit to this answer for the final bits.
So I am making this "drop-zone" for a website.
The user can drag and drop images over this area and all jpegs that are dropped on the area are displayed as thumbnailes. I made a List of all jpegs that are dropped on the area and that is working fine. Now everytime a new jpeg is added to that list I want to display all jpegs as thumbnailes of the size 100x150px.
Here is my code for that.
And here is a like to the fiddle http://jsfiddle.net/cJkYj/2/
function displayThumbnailes( ) {
//Clear the div.
var outerDiv = document.getElementById('fileChooserDiv');
while (outerDiv.hasChildNodes()) {
outerDiv.removeChild(outerDiv.lastChild);
}
var div = document.createElement('div');
outerDiv.appendChild(div);
//Go over the Files and add Thumbnails for all jpegs.
for( var i = 0; i < files.size(); i++) {
if( files.get(i).type == "image/jpeg") {
var reader = new FileReader();
reader.onloadend = function() {
var result = reader.result;
displayThumbnail( result, div );
}
reader.readAsDataURL(files.get(i));
}
}
}
function displayThumbnail( src, div ) {
var img = new Image();
img.onload = function () {
var cv = document.createElement('canvas');
cv.style.border = "1px solid #ffffff";
cv.width = 100;
cv.height = 150;
var ctx = cv.getContext( "2d" );
ctx.drawImage(img, 0, 0, 100, 150);
div.appendChild(cv);
}
img.src = src;
}
MY PROBLEM: I believe this code would display all thumbnailes in the area of the div but I only see the last one.
This looks like I am messing up some synchronisation or something.
"files" is an Object that manages the files dragged on the "drop-zone".
I want every Thumbnail to have his own canvas so I can add an onclick event to them later.
Any help would be appriciated ^^
Your code:
reader.onloadend = function() {
var result = reader.result;
displayThumbnail( result, div );
}
reader.readAsDataURL(files.get(i));
was failing because of the async onloadend callback. Each pass through the loop updated the outer reader variable, so each event used only the last reference.
You could either change your code to wrap that in a closure:
(function(reader) {
reader.onloadend = function() {
var result = reader.result;
displayThumbnail( result, div );
}})(reader);
or (preferred) change your code to use the event specific data :
reader.onloadend = function(evt) {
var result = evt.target.result;
displayThumbnail( result, div );
};
-- or using onload --
reader.onload = function (evt) {
var result = evt.target.result;
displayThumbnail(result, div);
}
reader.readAsDataURL(files.get(i));
works: example
I should also note that I rearranged your code to completely run within an onload handler.
Is there any way I could load an image via javascript and then have a callback fire when it is finished?
Thanks for any ideas.
Have you tried this?
var img = new Image();
img.onload = function(){ alert('loaded'); };
img.src = '/some/image.jpg';
UPDATE
sure you can set the background-image of an element with this. Use the onload event to do whatever you like!
// change background to image - only after image completely loaded
function setBackroundImage(node, imageUrl) {
var img = new Image();
img.onload = function() {
node.style.backgroundImage = imageUrl;
}
img.src = imageUrl;
}
setBackroundImage(document.getElementById('foobar'), '/some/image.jpg');
Here is the sample code to handle image load:
var img = document.createElement('img')
img.src = 'https://www.google.com/intl/en_com/images/srpr/logo3w.png'
$(img).load(function(){ alert('Image loaded')})
$('#container').append(img)