Issue with new Image() in Javascript - javascript

The code:
function CreateAndAnimateEnemyImg() {
var enemy = new Image();
enemy.src = 'enemy.jpg';
enemy.class = 'Enemy';
enemy.width = '30px';
enemy.height = '30px';
document.body.appendChild(enemy);
enemy.onload = function () {
alert('2. Image has fully loaded.');
$('.Enemy').animate({ 'right': '+=20px' });
}
}
$("#Start").click(function () {
CreateAndAnimateEnemyImg();
});
The weird behavior is that the alert is raised but no image is shown, nor the animation is working. Any help please?

Change your code:
enemy.className = 'Enemy';
enemy.width = '30'; // no px needed
enemy.height = '30';
http://jsfiddle.net/UqcqN/
You have two mistakes: if you set width property you don't have to provide units. And you should set className property instead of class.
It is also recommended to set src after onload handler.

You have to enemy.src = 'enemy.jpg'; AFTER you define: enemy.onload.

i think no need for giving string kind of 'px';
rtefer this http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_height
here is the complete demo Fiddle
function CreateAndAnimateEnemyImg() {
var enemy = new Image();
enemy.src = 'http://media.steampowered.com/apps/440/icons/icon_dueling_large.14fd9f2da0f24b2dfaac37d1600c821ddb6d3456.png';
enemy.class = 'Enemy';
enemy.width = '130';
enemy.height = '130';
document.body.appendChild(enemy);
enemy.onload = function () {
alert('2. Image has fully loaded.');
$('.Enemy').html(enemy);
console.log(enemy);
$('.Enemy').animate({ 'right': '+=20px' });
}
}
$("#Start").click(function () {
CreateAndAnimateEnemyImg();
});

Related

Canvas is flickering, img.src access

I got a game with falling pics
I push() the next func into an array
and my pics var bulletinare flickering, so I think it's probably I draw them a lot when use update() func
function rect () {
this.size = [rectSize.x, rectSize.y];
this.imagesSrc = rand(0, 1) ? 'bulletinYes' : 'bulletinNo';
this.position = [rand(0, w-rectSize.x), -rectSize.y];
this.bulletinValue = (this.imagesSrc === 'bulletinYes') ? 'bulletinYesValue' : 'bulletinNoValue';
}
rect.prototype = {
draw: function (){
var bulletin = new Image();
bulletin.src = imagesSrc[this.imagesSrc];
ctx.drawImage(bulletin, this.position[0], this.position[2], this.size[0], this.size[2]);
}
}
I've tried to put var bulletin outside the fuction like so
var bulletin = new Image();
bulletin.src = imagesSrc[this.imagesSrc]; <= ???
function rect () {
this.size = [rectSize.x, rectSize.y];
this.imagesSrc = rand(0, 1) ? 'bulletinYes' : 'bulletinNo';
this.position = [rand(0, w-rectSize.x), -rectSize.y];
this.bulletinValue = (this.imagesSrc === 'bulletinYes') ? 'bulletinYesValue' : 'bulletinNoValue';
}
rect.prototype = {
draw: function (){
ctx.drawImage(bulletin, this.position[0], this.position[1], this.size[0], this.size[1]);
}
}
but I have no idea how to change [this..imagesSrc] so it could work.
And also it is executed only once and pic are not randomizing for each pushed one.
Does anyone have any suggestion how to get rid of the flickering or change bulletin.src = imagesSrc[this.imagesSrc];
here's my github link if u want to see whole script
I just started my coding path, so thanks anyone who could answer this one:)
You create new image each time and trying to draw it before image is loaded.
Better way is prepare all images at start and just draw it.
Little changes in your code and all will work:
Prepare images:
var imagesSrc = {
ballotBoxImgSrc: 'img/ballotBox.png',
bulletinYes: 'img/yes.jpg',
bulletinNo: 'img/no.jpg'
};
var images = {
ballotBoxImgSrc: new Image(),
bulletinYes: new Image(),
bulletinNo: new Image()
}
for(let [name,value] of Object.entries(imagesSrc)) {
images[name].src = value;
}
Draw:
rect.prototype = {
draw: function (){
var bulletin = images[this.imagesSrc];
ctx.drawImage(bulletin, this.position[0], this.position[1], this.size[0], this.size[1]);
}
}

Display a loading icon while loading image

I would like to be able to display a GIF while the image is being loaded. Is this possible with the script I am using?
From what I understand I would use something like
$('#image').load { loadingimage.hide }
Here is my code:
$.get('http://192.168.1.69:8090/VirtualRadar/AirportDataThumbnails.json?icao=' + p.Icao + '&reg=' + p.Reg , function(res) {
var error = res.status;
if (error == "404") {
$("#image").attr('src', "placeholder.jpg");
$("#image2").attr('src', "placeholder.jpg");
$("#imageurl").attr('href', "//airport-data.com");
} else {
var imgUrl = res.data[0].image;
var imgHref = res.data[0].link;
$("#image").attr('src', imgUrl);
$("#image2").attr('src', imgUrl);
$("#imageurl").attr('href', imgHref);
}
})
Use the Image.onload attribute or attach an event listener.. load the loading wheel image first then display that while the larger image is loading...
function loadImage(src){
return new Promise(done=>{
var i = new Image();
i.onload = ()=>done(i);
i.src = src;
});
}
const loadImgSrc = "https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif";
const bigImgSrc = "https://www.gannett-cdn.com/-mm-/4252e7af1a3888197136b717f5f93523f21f8eb2/r=x1683&c=3200x1680/local/-/media/USATODAY/onpolitics/2012/10/03/bigbird-16_9.jpg";
loadImage(loadImgSrc).then(img=>{
img.style.maxWidth = "100%";
document.getElementById('myImg').appendChild(img);
loadImage(bigImgSrc).then(img=>{
img.style.maxWidth = "100%";
document.getElementById('myImg').innerHTML = '';
document.getElementById('myImg').appendChild(img);
});
})
<div id=myImg></div>

How do I change only one image out of many onclick with appendChild?

I'm currently learning JavaScript at my university, so I apologize if my code is terrible. I'm new to it.
I'm having an issue only changing one image onclick using appendChild. What I want to happen is that if the person clicks on the image whose rng is <= 0.89, then only that image is changed to a different image. Every thing I've tried has changed all of the images whose rng was <=0.89.
Example: I click the first image (img1) which has rolled a number greater than 0.9. If (img2) has rolled the same (greater than 0.9), then it also changes. I'd only want img1 to change. Here is only some of my code as the whole thing is about 150 lines and I think this bit gets my point across somewhat well:
function myFunction() {
var rng=Math.random();
var rng2=Math.random();
if (rng <= 0.89){
var img1=document.createElement('img');
img1.src='card2.gif';
img1.id="bad1";
img1.onclick = goodbye;
document.getElementById('card').appendChild(img1);
}
if (rng2 <= 0.89){
var img2=document.createElement('img');
img2.src='card2.gif';
img2.onclick= goodbye;
img2.id="bad2";
document.getElementById('card2').appendChild(img2);
}
if (rng >= 0.9) {
var img1=document.createElement('img');
img1.src='card3.gif';
img1.id="good1";
img1.onclick = hello;
document.getElementById('card').appendChild(img1);
}
if (rng2 >= 0.9){
var img2=document.createElement('img');
img2.src='card3.gif';
img2.onclick= hello;
img2.id="good2";
document.getElementById('card2').appendChild(img2);
}
}
Like I said, every thing I've tried to only change the image that was clicked has changed all images whose rng is <=0.89. The answer's probably really obvious, but I'm new to this, like I said.
Based on the comments, the only change that your code needs is to make .onclick set to a function instead of a string. This way we also pass this the element reference to your functions goodbye and hello. You can also use this to read the element properties if you wanted to. If this is not what your looking for let us know.
img1.onclick = function(){goodbye(this)};
Script
function goodbye(e) {
e.src = 'https://www.youtube.com/yt/brand/media/image/YouTube-logo-full_color.png'
}
function hello(e) {
e.src = 'https://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I.jpg'
}
function myFunction() {
var rng = Math.random();
var rng2 = Math.random();
if (rng <= 0.89) {
var img1 = document.createElement('img');
img1.src = 'card2.gif';
img1.id = "bad1";
img1.onclick = function () {
goodbye(this)
};
document.getElementById('card').appendChild(img1);
}
if (rng2 <= 0.89) {
var img2 = document.createElement('img');
img2.src = 'card2.gif';
img2.onclick = function () {
goodbye(this)
};
img2.id = "bad2";
document.getElementById('card2').appendChild(img2);
}
if (rng >= 0.9) {
var img1 = document.createElement('img');
img1.src = 'card3.gif';
img1.id = "good1";
img1.onclick = function () {
hello(this)
};
document.getElementById('card').appendChild(img1);
}
if (rng2 >= 0.9) {
var img2 = document.createElement('img');
img2.src = 'card3.gif';
img2.onclick = function () {
hello(this)
};
img2.id = "good2";
document.getElementById('card2').appendChild(img2);
}
}
jsfiddle if required

Animating canvas with a javascript constructor

Hello stackoverflow community!
First I must say that I dont have much experience with constructors.
So. What I am trying to do, is to animate a parachutist to fly from top to bottom of the screen.
I thought I could use a constructor to set up a parachutist:
var parachute = function() {
this.height = 35;
this.width = 30;
this.speed = 50;
this.xPos = Math.round(Math.random() * (window.width - this.width));
this.animate = function() {
this.img = new Image();
this.yPos = 0;
this.img.onload = function() {
ctxPara.globalCompositeOperation = 'copy';
ctxPara.translate(0, this.yPos);
ctxPara.drawImage(this.img, this.xPos, 0);
};
this.img.src = 'para.png';
this.yPos++;
};
};
This constructor is used in a function called 'fly':
var fly = function() {
var newParachute = new parachute();
setInterval(newParachute.animate, newParachute.speed);
};
And this 'fly' function is triggered when the window loads:
window.onload = function() {
var canvasBg = document.getElementById('canvasBg');
// I splitt the Background and the parachutists in two canvas elements
// handling the problem (to erase content and draw new content) with
// the canvas animation.
var canvasPara = document.getElementById('canvasPara');
ctxPara = canvasPara.getContext('2d');
canvasPara.width = window.width;
canvasPara.height = window.height;
canvasBg.width = window.width;
canvasBg.height = window.height;
fly();
clouds(); // background is loading here
};
What you should see, is a Parachutist flying down the screen. But unfortunately you don't...
Now, after that Long text. (Iam very sorry that it is so long :-( ) My question is: Do you know what I am doing wrong? Is my constuctor correct? Is, what i am trying to do, supposed to be written like this? Any advices or suggestions for a succesfull opportunity? (I hope my english isn't that terrible I think it is :-) )
Oh i forgot to mention the error. It's a TypeMissMatchError.
That means 'this.img' is not an img element at this line:
ctxPara.drawImage(this.img, this.xPos, 0);
Now, I followed the example of markE.
Instead of showing me a parachutist. It shows me an error in this line: ctxPara.drawImage(this.img, this.xPos, this.yPos);
var fly = function () {
var newParachute = new parachute();
newParachute.img.load.call(newParachute);
setInterval(newParachute.animate.call(newParachute), newParachute.speed);
};
var parachute = function () {
this.height = 35;
this.width = 30;
this.speed = 25;
this.xPos = Math.round(Math.random() * (window.innerWidth - this.width));
this.img = new Image();
this.yPos = 0;
this.img.isLoaded = false;
this.img.load = function () {
this.img.isLoaded = true;
};
this.img.src = 'parachute.png';
this.animate = function () {
if (this.img.isLoaded) {
ctxPara.clearRect(0, 0, canvasPara.width, canvasPara.height);
ctxPara.drawImage(this.img, this.xPos, this.yPos); // ERROR: 'Unknown Error'.
this.yPos++;
console.log('animating');
}
};
};
I am stuck again. But now i don't even know the reason... Please help!?
Demo: http://jsfiddle.net/m1erickson/ym55y/
A couple of issues:
(1) To get the window width you can use:
window.innerWidth
(2) setInterval calls newParachute.animate.
setInterval(newParachute.animate, newParachute.speed);
But this inside animate the window object--not the Parachute object.
To give the correct this to animate you can use the call method like this:
var newParachute = new parachute();
setInterval(function(){newParachute.animate.call(newParachute);}, newParachute.speed);
(3) You need to deal with clearing previously drawn images or they will still show on your canvas.

Getting width of image (by URL) outside function w/ JavaScript

I'm trying to get the width of two images based on their URLs (so, actual image size). I'm able to do that in such a way so as to pop up an alert based on the results, but anything outside of the actual function results in an undefined value for the widths of the two images.
var w1 = "";
var w2 = "";
var img1 = new Image();
img1.onload = function() { w1 = this.width;};
img1.src = "URL1";
var img2 = new Image();
img2.onload = function() { w2 = this.width;};
img2.src = "URL2";
alert (w1 + " and " + w2);
How do I use w1 and w2 outside of the functions that set them to this.width?
Ideally I'd like to compare them and later on use the larger one. But I can't even get them to show with their correct values in the alert (above).
Thanks in advance!
Adendum:
var img1 = new Image();
var img2 = new Image();
var one, two;
img1.src = "img1.jpg";
img2.src = "img2.jpg";
img1.onload = function() {img2.onload = function() {compareWidth(img1.width, img2.width);}}
var finalchoice;
var compareWidth = function (width1 ,width2){
if(width1 > width2){
finalchoice = img1.src;
alert(finalchoice);
return finalchoice;
}
else{
finalchoice = img2.src;
alert(finalchoice);
return finalchoice;
}
}
Idea being then to use final choice later in the .js file.
The alert (w1 + " and " + w2);
statment is executed before the image is loaded that's why the result is displaying undefined.
To compare the width of two images you can use this code.
<!DOCTYPE html>
<html>
<head>
<body>
</body>
<script>
var img1 = new Image();
img1.src = "w3javascript.gif";
img1.onload = function() {
document.body.appendChild(img1); //this is optional you can remove it
compareWidth(this.width);
}
var img2 = new Image();
img2.src = "author.jpg";
img2.onload = function() {
document.body.appendChild(img2); //this is optional you can remove it
compareWidth(this.width);
}
var w1;
var compareWidth = function (width){
//here you can do operation with width and height
if(typeof w1 == 'undefined'){
w1 = width;
}else{
if(w1 < width){
alert('do one thing');
}else{
alert('do other thing');
}
}
}
</script>
</html>
i would recommend using jQuery...
Just load jQuery ... > like <script src="{jquery-lib-path}"></script>
and do something like
var imgWidth = img.width():

Categories

Resources