Javascript Object Finding Game - javascript

im currently having a big problem with a javascript little game im programming. Essentially the player finds specific objects, but to make it easier i want to make a menu to show which objects are there to find
for (let i = 0; i < figuresCount; i++) {
var img = document.createElement("img");
img.src = "figure" + randomNumber(1,10)+ ".svg";
img.id = "figure"+i;
var div = document.getElementById("main");
div.appendChild(img);
document.getElementById("figure"+i).style.top = randomNumber(10, 95) + "%";
document.getElementById("figure"+i).style.left = randomNumber(1, 90) + "%";
document.getElementById("figure"+i).style.width = randomNumber(30, 60) + "px";
document.getElementById("figure"+i).style.transform = "rotate("+ randomNumber(0,360) +"deg)";
document.getElementById("figure"+i).style.position = "fixed";
document.getElementById("figure"+i).addEventListener("click", findFigure);
}
this is the loop where the objects are taken and shown on the playing field. The problem im having is saving the same randomized photos in the menu. Another thing that is difficult is that when a specific object is found, then the object in the menu should disappear too. Can someone help me with this?
I tried creating another variable and saving it there but it does not work.
var menu = document.getElementById("menu");
menu.appendChild(img);

Related

Javascript remove image on click

var b = 1;
for(var i= 0; i < 5; i++){
fisk(b);
}
function getRandomPosition(element) {
var x = document.body.offsetHeight-element.clientHeight;
var y = document.body.offsetWidth-element.clientWidth;
var randomX = Math.floor(Math.random() * x);
var randomY = Math.floor(Math.random() * y);
return [randomX,randomY];
}
function fisk(skala) {
var img = document.createElement('img');
img.setAttribute("style", "position:fixed;");
img.setAttribute("src", "http://i.imgur.com/K9egEbW.jpg");
document.body.appendChild(img);
var xy = getRandomPosition(img);
img.style.top = xy[0] + 'px';
img.style.left = xy[1] + 'px';
}
With this code above i have made a tiny game where i am supposed to click on some fished that spawns with this code and when you click them all you win. But i'm having trouble finding out how to make the images disappear when i click them. Here is a jsbin link that shows all i've done so far so it's easier to understand. https://jsbin.com/josamuxoce/edit?html,css,js Anybody have a clue on how to make the fishes that spawn disappear when i click on them with the fishing rod?
Thanks
Add $(img).click(function(){ $(this).remove();}); to function fisk(skala);
But. img will never get click becaurse all clicks will be handled by #fiskespo.
Use fiskespo image as cursor image instead of extended img object (Using external images for CSS custom cursors). Should work;

javascript Larger image viewer

i have a set of small sized images on the browser. What i want to do is when i click on the image a larger format of the image clicked will show up in a div above. here is javascript code. The code below shows an empty image. how do i fix this? I dont want jquery to do this.
//for images
var largeImageViewer = document.getElementById('large-image-viewer');
var smallImages = document.querySelectorAll('.small-images');
for(i = 0; i < smallImages.length; i++){
smallImages[i].addEventListener('click', function(event){
if (event) {
var img = document.createElement("img");
img.style.width = 500 + "px";
img.style.height = 500 + "px";
img.src = smallImages.src;
largeImageViewer.appendChild(img);
};
});
}
Inside an event handler the current element can be get by 'this' keyword.
img.src = this.src;

function is not working properly

I have a problem with my functions for when a enemy shoots a laser. I have done so much debugging on this, i just cannot figure out why it is not working.
When i have my code like this it will shoot to the top of my playArea but not to the bottom (boundary is spelt wrong because i done it from the beginning)
for (var i = 0; i < enemylasers.length; i++){
if(parseInt(enemylasers[i][0].style.top) > playArea.topBoundry){
enemylasers[i][1] -= laserSpeed;
enemylasers[i][0].style.top = enemylasers[i][1] + 'px';
}else{
playArea.removeChild(enemylasers[i][0]);
enemylasers.splice(i,1);
}
}
When i change some of the code around to what i think might be right, it isnt and just does not make the lasers shoot anywhere. here is what i changed it to.
for (var i = 0; i < enemylasers.length; i++){
if(parseInt(enemylasers[i][0].style.top) > playArea.bottomBoundry){
enemylasers[i][1] += laserSpeed;
enemylasers[i][0].style.top = enemylasers[i][1] + 'px';
}else{
playArea.removeChild(enemylasers[i][0]);
enemylasers.splice(i,1);
}
}
This is what creates my enemies laser
function createenemylaser(){
if(enemylasers.length < enemymaxlasers){
var laserpush = Math.floor(Math.random()*enemies.length);
var laser = enemylaser();
laser.classList.add('enemylaser');
laser.style.top = enemies[laserpush][1] + 'px';
laser.style.left = parseInt(enemies[laserpush][0].offsetLeft) +'px';
playArea.appendChild(laser);
enemylasers.push([laser, enemies[laserpush][1]]);
}
}
setInterval(createenemylaser, 2000);
And this is my enemies lasers array
enemylasers=[],
enemylaserspeed = 5,
enemymaxlasers= 8,
And this is what creates the div for my enemy laser
function enemylaser(){
return document.createElement('div');
}
I hope someone can help, i am not that experienced in javascript but i know quiet abit.
Since #Chips_100 suggested I should post my solution from the comments section here, here it is:
You needed to change parseInt(enemylasers[i][0].style.top) > playArea.bottomBoundry to parseInt(enemylasers[i][0].style.top) < playArea.bottomBoundry as you have reversed the direction your lasers are travelling in.

IE7-8 ignoring selectively ignoring jquery image .load() and/or contents of .load function

I'm writing a rather complex AJAX driven menu with multiple levels that animate around allowing a user to navigate a complicated tree structure at some point I had to add a function that auto centers (vert and horz) the images associated with each item on the menu tree. In order to measure the images and position them accordingly I must first write them to a hidden div ("#tempHolder") once they .load() I can then get their dimensions, calculate my offsets and then write the images to the DOM in the appropriate place.
This all works A Okay in the standards compliant browsers but IE7-8 seem to only process the .load() command when they feel like it. (homepage the menu loads okay, first visit to a sub-page breaks the menu, refreshing said page fixes it again...etc.). I restructured my function to make the .load() declaration early because of the advice I read here (http://blog.stchur.com/2008/02/26/ie-quirk-with-onload-event-for-img-elements/) but that doesn't seem to have worked. I also added e.preventDefault because of a stackOverflow thread that said this might prevent IE from caching my load statements.
Here is the function causing the issues:
if (this.imagePath != "") {
runImage = function (imagePath, $itemEle) {
var $itemEleA = $itemEle.find('a');
var image = new Image();
//$thisImage = $(image);
$(image).load(function (e) {
//alert('image loaded')
$(image).evenIfHidden(function (element) {
//alert('even if hidden');
////////////console.log($thisImage);
var elementWidth = element.width();
var elementHeight = element.height();
this.imageHeight = elementHeight;
this.imageWidth = elementWidth;
//alert('widthoffset = ' + widthOffset + 'imagewidth = ' + imageWidth + 'this.imageWidth = ' + this.imageWidth + 'elementWidth = ' + elementWidth);
var imagePaddingWidth = 230 - imageWidth;
var widthOffset = imagePaddingWidth / 2;
widthOffset = widthOffset + "px";
element.css("left", widthOffset);
var imagePaddingHeight = 112 - imageHeight;
if (imagePaddingHeight < 0) {
var heightOffset = imagePaddingHeight;
heightOffset = heightOffset + "px";
element.css("top", heightOffset);
}
if (imagePaddingHeight > 0) {
var heightOffset = imagePaddingHeight - 18;
heightOffset = heightOffset + "px";
element.css("top", heightOffset);
}
});
$(this).appendTo($itemEleA);
e.preventDefault();
return image;
});
image.src = imagePath;
//var tempvar = $itemEle.find('a');
$(image).appendTo("#tempHolder");
}
this.image = runImage(this.imagePath, $itemEle);
}
Since this is for a big client and the site is not yet live I can't show the site but I'll try to throw up some screen shots later.
Any help is greatly appreciated.
It is quite a common problem, and if the images are already in the cache some browsers (shall I say directly - IE?) fails to trigger load events on them. Hence there is a technique for a workaround.
// After this line of your code
image.src = imagePath;
// put this
if (image.complete || image.naturalWidth > 0) { // if image already loaded
$(image).load(); // trigger event manually
}

replacing images inplace

I have a array of static images that I am using for an animation.
I have one frame image that I want to update the image of and I have seen a lot of tutorials on animating images with javascript just simply update the source of an image.
frame.src = animation[2].src; etc
When I look at the resource tracking in chrome, it doesnt look like they are getting cached even thought the web browser does download the image more than once but not once for each time it is displayed, so there is still some browser caching going on.
What is the best way to replace the frame image object with another image?
Well, you can either position all images absolute and give them a z-index, then use jQuery/JS to shuffle their z-indexes, bringing a new one to the top in a cross fader style,
or you can take all the id's and fadeone in slightly faster than the last one fades out.
Like so:
function fader(func) {
var currID = $('#mainimg ul').data('currLI');
var currLiStr = '#mainimg ul li#' + currID;
img = $(currLiStr).find('img').attr('src');
nextID = (currID == 'six') ? 'one' : $(currLiStr).next().attr('id');
nextLiStr = $('#mainimg ul li#' + nextID);
$(currLiStr).fadeOut(3000);
$(nextLiStr).fadeIn(2000).find('div.inner').delay(3000).fadeIn('slow').delay(6000).fadeOut('slow');
$('#mainimg ul').data('currLI',nextID);
}
Note 'six' is the id of the last li, reseting it back to one, but if you do $('#mainimg ul li:last').attr('id'); and $('#mainimg ul li:first').attr('id') to get the last and first id's, you can allow it to cope with any amount of images (obviously this is with li's given id's one, two and so on, but if you are finding out the last and first id you could use any structure.
Or you can set a ul width a width of all the li's multiplied, and give the li's the width of the images, and set overflow to hidden, then use JS to pull the li's left by the width of 1 li on each iteration in a slider like I have done here: http://www.reclaimedfloorboards.com/
There are loads of options
I ended up using jquery's replaceWith command and gave all the frames a class "frame" that i could select with $('.frame') which happened to only select visible frames.
<script type="text/javascript">
var animation = [];
var firstFrame = 1;
var lastFrame = 96;
var animationFrames = 16;
var loadedImageCount = 0;
$(function() {
$("button, input:submit",'#forecastForm').button();
$("#progressbar").progressbar({
value: 0
});
$('#id_Species').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_Layer').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_StartTime').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
$('#id_EndTime').attr('onChange', 'loadAnimation($(\'#id_Species\').val(),$(\'#id_Layer\').val(),$(\'#id_StartTime\').val(),$(\'#id_EndTime\').val())' )
});
if (document.images) { // Preloaded images
loadAnimation('Dry_GEM',1,1,96);
}
function rotate(animation, frame)
{
if (frame >= animation.length)
frame = 0;
$('.frame').replaceWith(animation[frame]);
window.setTimeout('rotate(animation,'+eval(frame+1)+')',150);
}
function loadAnimation(species, layer, startTime, endTime)
{
layer = Number(layer);
startTime = Number(startTime);
endTime = Number(endTime);
if (startTime > endTime)
{
swap = startTime;
startTime = endTime;
endTime = swap;
delete swap;
}
for (i=0;i<animation.length;i++)
delete animation[i];
delete animation;
animation = []
$('#progressbar').progressbar({value: 0});
loadedImgCount = 0;
animationFrames = endTime - startTime + 1;
for(i=0;i < animationFrames;i++)
{
animation[i] = new Image();
animation[i].height = 585;
animation[i].width = 780;
$(animation[i]).attr('class','frame');
animation[i].onload = function()
{
loadedImgCount += 1;
$('#progressbar').progressbar({value: eval(loadedImgCount / animationFrames * 100)});
};
animation[i].src = 'http://[[url]]/hemi_2d/' + species + '_' + layer + '_' + eval(i+startTime) + '.png';
}
}
</script>
The easiest way to do it is create a separate hidden image for each frame. Something like this:
var nextImage = (function(){
var imagePaths='basn0g01.png,basn0g02.png,basn0g04.png,basn0g08.png'.split(','),
imageHolder=document.getElementById('custom-header'),
i=imagePaths.length, imageIndex=i-1, img;
for (;i--;) {
img=document.createElement('img');
img.src='http://www.schaik.com/pngsuite/' + imagePaths[i];
if (i) img.style.display='none';
imageHolder.appendChild(img);
}
return function(){
imageHolder.childNodes[imageIndex].style.display='none';
if (++imageIndex >= imageHolder.childNodes.length) imageIndex=0;
imageHolder.childNodes[imageIndex].style.display='inline-block';
}
}());
Try this example on this page; paste it in the console and then call nextImage() a few times. Watch the top of the page.
edit
If you already have all the images in your HTML document, you can skip most of the above and just do something like this:
var nextImage = (function(){
var imageHolder=document.getElementById('custom-header'),
images=imageHolder.getElementsByTagName('img'),
i=images.length, imageIndex=0, img;
for (;i--;) if (i) images[0].style.display='none';
return function(){
imageHolder.childNodes[imageIndex].style.display='none';
if (++imageIndex >= imageHolder.childNodes.length) imageIndex=0;
imageHolder.childNodes[imageIndex].style.display='inline-block';
}
}());

Categories

Resources