I attached an onload event to an imgage created by new image();
But the onload event seems to be never fired. The console.log inside the function which should be run when onload is fired is never displayed.
I also tried to use addEventListener instead of .onload. but it doesn't work either.
function init(){
var main_canvas = document.getElementById('main_canvas');
var bg_canvas = document.getElementById('background_canvas');
if(main_canvas.getContext){
var ctx = main_canvas.getContext('2d');
var bg_ctx = bg_canvas.getContext('2d');
let ball = new Image();
let box = new Image();
console.log(ball);
ball.onload = function() {
console.log('positiv');
bg_ctx.drawImage(box,150,100);
bg_ctx.drawImage(box,150,600);
ctx.drawImage(ball,350,125);
}
ball.src = 'ball.png';
box.src = 'box.png';
}
}
window.addEventListener('load', init);
Expected output should be: 1) (because of console.log(ball);) This works fine.
2) output: positiv (because ball.onload is fired) BUT THIS NEVER HAPPENS!!
Related
I need to validate one file field with required width,height and if file has not uploaded using JavaScript but its not happening like this. Here is my code:
<input type="file" name="copImage" id="copImage" class="form-control" value="" onchange="setBackgroundImage(event);">
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
};
console.log('size bg',backImageHeight,backImageWidth);
}
Here I could not get the file height and width. I also to check the if file has not uploaded.
Pu the log statement inside the onload function. This is because you are trying to access the variable outside its scope, else define those variables outside onload function
bg.onload = function() {
var bgLoaded = true,
backImageHeight = this.height,
backImageWidth = this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
DEMO
suppose i have one button and without selecting file if I am clicking
on the file alert should say to select the file.
Seems you cannot do that with onchange event handler because if file is not loaded. nothing has changed and so function wont fire. In that case you can create a variable & update its state on file upload. On clicking of the button check the variable state
var isFileLoaded = false;
function setBackgroundImage(fileValue) {
var url = URL.createObjectURL(fileValue.files[0]);
bg = new Image();
if (fileValue.value !== '') {
bg.src = url;
bg.onload = function() {
bgLoaded = true;
isFileLoaded = true;
backImageHeight = this.height;
backImageWidth = this.width;
console.log('size bg', backImageHeight, backImageWidth);
};
}
}
function buttonClick() {
if (isFileLoaded) {
} else {
alert('No file selected')
}
}
DEMO 2
Hello You just need to log your height and width inside bg.onload function.these are outside of the scope of variables.thats why you not getting the height and width like this
function setBackgroundImage(e){
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
}
Everything is fine in your code, you need to include console.log() within bg.onload block only like this .
function setBackgroundImage(e)
{
var url = URL.createObjectURL(e.target.files[0]);
bg = new Image();
bg.src = url;
bg.onload = function () {
bgLoaded = true;
backImageHeight=this.height;
backImageWidth=this.width;
console.log('size bg',backImageHeight,backImageWidth);
};
}
function isFileSelected()
{
return document.getElementById('copImage').files.length > 0;
}
You can use isFileSelected() function to know whether file is selected or not .
I'm creating a canvas and using drawImage() to draw an inline svg. Everything works okay but I'm stuck because of the below problem...
My problem is that the onload handler not responding in IE?? Rhis works in FF and chhrome. How do I fix it to work in IE 9 upwards?
img2.onload = function() {
console.log("load");
}
jsFiddle
function createme() {
var test = $('<canvas />', { id : 'mycanvs' })
$('#album').append(test);
var svg2 = document.getElementById('sSource').innerHTML,
vms = test[0], //canvas
ctx2 = vms.getContext('2d');
svgToImage(svg2);
function svgToImage(svg2) {
var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
img2 = new Image;
alert("just before onload")
img2.onload = function() {
console.log("load"); // does not show
}
img2.src = nurl;
}
}
I don't have an IE VM running at the moment, but according to their docs the handler has to be defined before the object itself:
To ensure that an event handler receives the onload event for these
objects, place the script object that defines the event handler before
the object and use the onload attribute in the object to set the
handler.
I don't see why your code wouldn't work in IE, but this fiddle tweaks it slightly so your handler is defined before you create the image object... give this a try:
function createme() {
var test = $('<canvas />', { id : 'mycanvs' });
var onloadHandler = function() {
console.log("load");
};
$('#album').append(test);
var svg2 = document.getElementById('sSource').innerHTML,
vms = test[0], //canvas
ctx2 = vms.getContext('2d');
function svgToImage(svg2) {
var nurl = "data:image/svg+xml;utf8," + encodeURIComponent(svg2),
img2 = new Image;
img2.onload = onloadHandler
img2.src = nurl;
}
svgToImage(svg2);
}
createme();
https://jsfiddle.net/z769z7af/10/
I understand that onclick() in html with parenthesis calls automatically. But in my situation, I want to pass a parameter into the onclick function(specifically, the element clicked). So how do I manage this without having onclick fired when the page loads? In addition, the onclick method does not fire after its automatically firing upon loading. My code is below:
for (i = 0; i < returnPostPhotoSrcs().length; i++) {
// var photosArray=returnPhotoNames()
// var imgName=photosArray[i]
var imgSrcArray=returnPostPhotoSrcs();
var imgSrc=imgSrcArray[i]
var postNamesArray=returnPostNamesArray();
var postName=returnPostNamesArray[i]
var img=img_create(imgSrc,postName,'')
img.style.width=returnPostHeight();
img.style.height=returnPostWidth();
img.className="postImage";
img.onmousedown=playShout(img);
var postNamesArray=returnPostNames();
var innerSpan = document.createElement('span');
innerSpan.onmousedown=playShout(innerSpan); //problem line
var text = postNamesArray[i];
innerSpan.innerHTML = text; // clear existing, dont actually know what this does
var outerSpan = document.createElement('span');
outerSpan.className="text-content";
outerSpan.onmousedown=playShout(outerSpan); //another problem line, also doesnt call onclick
var li = document.createElement('li');
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(img)
outerSpan.appendChild(innerSpan)
li.appendChild(imgSpacer)
imgSpacer.style.opacity="0"
// if (i>0 && i<returnPostPhotoSrcs().length-1) {
// hackey
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(imgSpacer)
li.appendChild(outerSpan)
imgSpacer.style.opacity="0"
// }
var outerDiv = document.getElementById("postDivOuter");
outerDiv.appendChild(li)
}
Adding onto this you could also do:
img.onmousedown= function(e) { playShout(e) };
//for playshout
playshout = function(e) {
var element = e.target; //this contains the element that was clicked
};
The function fires because you are calling it. You need to use a closure
img.onmousedown= function() { playShout(img) };
As others have shown, you can create an anonymous function, or another option is to use .bind():
innerSpan.onmousedown = playShout.bind(null, innerSpan);
I try to load an image as such:
var img = new Image();
img.src = 'mars.png';
img.onLoad = callback;
function callback(){
// doesnt fire
alert("loaded");
}
the callback never fires, whats the workaround?
You MUST define the onload BEFORE you change the src and event handlers are lowercase so it is spelled onload
var img = new Image();
img.onload = callback;
img.src = 'mars.png';
function callback(){
alert("loaded");
}
or as I prefer it
var img = new Image();
img.onload = function(){
alert("loaded");
}
img.src = 'mars.png';
Have you tried these?
var img = new Image();
img.src = 'mars.png';
img.onLoad = function(){
// doesnt fire
alert("loaded");
};
mplungjan is right you can use these instead:
img.onload = function(){
// doesnt fire
alert("loaded");
};
with lower l in onLoad
I am trying to load a new image every time the previously loaded image has finished loading.
The function create_photo_list works correctly. It creates an array of the photos that need to be loaded. If none need to be loaded then the array is empty. The problem is, when there are no more items to load the it keeps calling the load_next_photo function.
The reason I call the registerEventHandler every time in the function is because if I don't, the function is not called when the next photo loads.
function registerEventHandler(node, event, handler) {
if (typeof node.addEventListener == "function")
node.addEventListener(event, handler, false);
else
node.attachEvent("on" + event, handler);
}
// Remove an HTML element event handler such as onclick
// ex: unregisterEventHandler($("textfield"), "keypress", showEvent);
function unregisterEventHandler(node, event, handler) {
if (typeof node.removeEventListener == "function")
node.removeEventListener(event, handler, false);
else
node.detachEvent("on" + event, handler);
}
function load_next_photo() {
var loading_list = create_photo_list();
alert(loading_list.length);
if (loading_list.length > 0) {
img[loading_list[0]]['loaded'] = 1;
registerEventHandler($("load_img"), "onload", load_next_photo());
$("load_img").src = img[loading_list[0]]['img'];
}
else {
alert("nothing");
unregisterEventHandler($("load_img"), "onload", load_next_photo())
}
unregisterEventHandler($("load_img"), "onload", load_next_photo())
}
Can't get my head around what you currently have, but such code works just fine:
var _images = ["image1.jpg", "image2.jpg", "image3.jpg"];
var _index = 0;
window.onload = function() {
LoadImage();
};
function LoadImage() {
//stop condition:
if (_index >= _images.length)
return false;
var url = _images[_index];
var img = new Image();
img.src = url;
img.onload = function() {
_index++;
LoadImage();
};
document.getElementById("Container").appendChild(img);
}
This will add the images to the container (element with ID Container) one by one, live test case: http://jsfiddle.net/yahavbr/vkQQ7/
This is plain JS, feel free to ask about any part for elaboration. :)