Javascript, need to change background image based on switch/variable - javascript

I am making a computer game on Twine, which accepts html, javascript, css.
I am trying to display images based on the state of the game.
This code below, works correctly i shows all 3 images overlapping correctly.
However, i want to display other images based on game state. For example if the player is at 20% health, it should display 2a.pgn instead of 2.pgn
or if it is poisoned, it should show 3a.pgn instead of 3.
And so on and so on, it does not make sense having to specify all possible combinations. Instead i just want to change a single layer at a time based on a variable/switch.
<html>
<div class="a1"></div>
<style>
.a1 {
width: 100%;
height: 1000px;
background-image: url(3.png),url(2.png),url(1.jpg);
background-repeat: no-repeat;}
</style>
</html>
Could you please help?
Thank you very much.
Cheers,

There are multiple ways - setting url() (and preloading everything on load), changing visibility, opacity or z-index, but if you want to stick with multiple backgrounds:
//imageIndex - your image for given HP
//imagesLen - images count
var HPimgArr = Array(imagesLen).fill('-9999px 0');
HPimgArr[imageIndex] = '0 0';
document.querySelector('.a1').style.backgroundPosition = HPimgArr.join(', ')

If you are refering to Javascript try this (you need jQuery for this):
var maxHealth = 10;
var health = 10; //He is apparently at full health
function updateHealth(newHealth){
health = newHealth;
if(health < maxHealth / 5) {
var stats = $('.a1').css('background-image').split(','); //Put every different stat in array
stats[1] = 'url(2a.png)';
$('.a1').css('background-image', stats.toString());
}
}
Whenever you want to change his health call updateHealth(...).
I haven't tested this but something along these lines should work.

Related

use JavaScript to toggle between different "crops" of a single large image

So I have been reading up on dozens upon dozens of Javascript zoom components, but none of them do what I am looking for, so I'm curious where to find such a component (if one exists) or how to code it myself.
The goal is to download a single large (1000x1000) image to the browser. Then within the browser, the image would have three presentation states within the same element container that the user can toggle between by clicking on some page element.
State 1 (default): See the entire image, but scaled down to fit within a 500x500 container (i.e. shrunk, but not cropped). For example (not to scale, but for comparison with other states):
State 2: See the middle 50%, centered, in the same container (i.e. actual size, and cropped). For example:
State 3: See the middle 25%, centered, in the same container (i.e. enlarged, and cropped quite a bit). For example:
And I would put the script that toggles between these three states in the click of some page element, such as a button.
Can any one offer a link to a component that does this, or suggestions on how the method that might accomplish it?
Thanks for any help!
I will go down on leveraging some CSS here.
For first case:
1) create a DIV which is 500x500, and set the background image to the file. Make sure you set background-size:contain property as well on the div.
2) For the second case I will remove the background-size:contain
3) The third case I will set the `background-size:200%;'
JSFiddle
If what you've described is really all you want to do it can be easily achieved with some CSS and a few lines of javascript:
var container = document.querySelector('.image-zoom'),
zoomBtn = document.getElementById('zoom-it'),
i = 0;
function clickHandler() {
if (i === 0) {
container.classList.add('zoom-2x');
i++;
} else if (i === 1) {
container.classList.add('zoom-4x');
i++;
} else {
container.classList.remove('zoom-2x');
container.classList.remove('zoom-4x');
i = 0;
}
}
zoomBtn.addEventListener('click', clickHandler);
.image-container, .image-zoom {
width: 250px;
height: 250px;
}
.image-container {
overflow: hidden;
}
.image-zoom.zoom-2x {
transform: scale(2);
}
.image-zoom.zoom-4x {
transform: scale(4);
}
<div class="image-container">
<div class="image-zoom" style="background-image:url(http://lorempixel.com/250/250)">
</div>
</div>
<button id="zoom-it">zoom image</button>
This assumes you know the dimensions of the image, which if you're using a CMS you can likely easily get and insert them inline on the .image-zoom and .image-containerelements.
jsFiddle
EDIT
jsFiddle 2
Modified the jsfiddle to be closer to what your question asked (initial state of the image is contained within the square and not cropped any amount.)

Background overlapping issue

I'm building a questionnaire that asks 10 questions and keeps a score, called total. I want so that if the total < 10, the screen turns red, however I had to remove the wallpaper that was there previously:
/*body{
background-image: url("twins.jpg");
}*/ <-- which is now a comment
So that this code would work:
if (total < 10){
alert("...RED SCREEN OF DEATH!");
document.body.style.backgroundColor = "#AA0000";
}
So now, when a user scores lower than 10, the screen turns red successfully, however that's now just half of the issue solved.
My next issue is that I want twins.jpg to be my background before the screen turns red, meaning I have twins.jpg as my wallpaper, then when total < 10, screen turns red.
My question is, what is the correct way to do this so that I can still see my background change red when total < 10 ? When I use this:
body{
background-image: url("twins.jpg");
}
It changes the background to twins.jpg, but overlaps the red when it changes colour, therefore I cannot see it.
The best way to solve this would probably be that you create a <div id="redbg"></div> around your content which is the same size than your <body> element (by adding a height and width of 100%).
You then add the background color to the new div:
if (total < 10){
document.getElementById('redbg').style.backgroundColor = "#AA0000";
}
As soon as you want to remove the background color, you could do it by making it transparent:
document.getElementById('redbg').style.backgroundColor = "transparent";
In CSS, properties like background and its properties like it do not override each other. If you set the image, then color, they will not over one each other.
To solve you problem, instead of using "background-image" and "background-color", change them both to just "background" as this will override the other choice.
Let me know if this solves your problem! (COMMENT)
Bryce

CSS3/HTML5/JS - How can I create an animated texture background with slide effect?

You may have seen that in some games there's moving background that goes on diagonal. Take a look at this example of Megaman x Storm Eagle Stage https://youtu.be/Wfm3ZvcxOKQ?t=1m33s, the clouds are moving on from up to bottom, right to left (Diagonal). I need to achieve the same effect using CSS3 or any kind of javascript, with a tile texture.
Where can I find a tutorial teaching how to make that? I found some, but they are for creating dynamic objects.
Hi this could be solved using basic javascript or any javascript library. I will give a small working example or you can just jump to this js fiddle https://jsfiddle.net/lesshardtofind/a2Lx51xy/
In your html you just need one element.
<div class='background'></div>
The class is for us to select it. First with some css lets make it so we have a picture and can see it.
.background{
background-image: url('yourImageUrl.com/image.png');
height: 500px;
width: 500px;
}
So background image applies your texture, height, and width will apply values so that you can see the div otherwise it would be 0 with no actual markup inside.
Now for the fun part. JavaScript can grab this div element and apply a style. Normally I would do this in jQuery, but since you just specified javaScript I'll keep external libraries out of it.
var x = 0;
var y = 0;
var xSpeed = 5;
var ySpeed = 5;
var interval = setInterval(function(){
var xVal = x + 'px';
var yVal = y + 'px';
var bg = document.getElementsByClassName('background')[0].style.backgroundPosition = xVal + " " + yVal;
x-=xSpeed;
y+=ySpeed;
}, 100);
To explain this I set x and y which are my background coordinates to 0 as a start. It is good to set default values otherwise you will invite undefined behavior. xSpeed, and ySpeed are just variables you can change the value of speed up or slow down the animation. interval is the variable that stores the interval set by the setInterval function. setInterval accepts a function and a time value as arguments. The function will be called at each interval and the time is the amount of time to wait until calling the function again.
document.getElementsByClassname('background') returns an array which I access with the [0] index. Then style allows you to apply a value to your backgroundPosition. Notice that I applied the 'px' to the end of each number so that they would be a string such as "3px 5px" this is how they are expected.
Then speed is applied using -= and +=. Since the dom starts at 0, 0 in the left corner of your browser then adding to Y will move down and subtracting from X will move left.
Lastly this works because background is set by default to repeat so the image will continue to just driftdownward and to the left. If you supply a tiled image you won't see the seams in between one repeat and the next.
Edit: Add fullscreen
You can add the fullscreen to your child object by making sure that its parents also have a set width and height. So changing your css to.
body, html{
height: 100%;
width: 100%;
}
.background{
background-image: url('http://bgfons.com/upload/sky_texture1998.jpg');
height: 100%;
width: 100%;
border: 1px solid red;
}
On % heights you need a parent node to inherit height from.

CSS3 timed animation of background image

I am pretty new to CSS and HTML, but I am learning the ropes. Right now, I have a background image on my header section and I am trying to turn this into a slideshow with 3-4 images shuffling through on a timer.
I have seen some tutorials that use images through HTML, but the way I have set it up is I have my CSS property background-image set as my image.
If this doesnt make sense, here is the CSS
.global-header {
min-height:600px;
background-image: url("Assets/BGImages/head_sandwichman.jpg");
background-size: cover;
text-align: center;
and the HTML
<header class="container global-header">
<div class="inner-w">
<div class='rmm' data-menu-style = "minimal">
<ul>
<li>HOME</li>
<li>MENU</li>
<li>FIND US</li>
<li>ABOUT</li>
</ul>
</div>
<div class="large-logo-wrap">
<img src="Assets/Logos/Giadaslogoindexwhitebig.png" />
</div>
</div>
Thanks for the help!
Use following
<script>
//Here use Array of images ,which you want to show, Use path you want.
var images=new Array('Assets/BGImages/head_sandwichman1.jpg','Assets/BGImages/head_sandwichman2.jpg','Assets/BGImages/head_sandwichman3.jpg');
var nextimage=0;
doSlideshow();
function doSlideshow()
{
if(nextimage>=images.length)
nextimage=0;
$('.global-header').css('background-image','url("'+images[nextimage++]+'")').fadeIn(500,function(){setTimeout(doSlideshow,1000);});
}
</script>
You would not be using HTML and CSS for carousel. While some cool experiments are out there I would shy away from using that on a production site. You will most likely be using jQuery. If you are new to front-end development and want to set up the slider and move on to the rest of your project, I'd recommend using a plugin.
Here is a popular jQuery plugin you can use: http://dev7studios.com/plugins/nivo-slider/
If you want to learn how to create your own, try following a tutorial that creates a similar slider. Then try playing around with the code to get it to the exact state you want.
Here's a an example of said tutorial: http://paulmason.name/item/simple-jquery-carousel-slider-tutorial
I think depending on the animation you are doing depends on the technique you could use.
if you are sliding the images you could use CSS3 animations to slide between the images. But this means you would have to make one large image that contains all your images and you change the background image position on a cycle.
This might be of some help:
http://designshack.net/articles/css/infinitephotobanner/
or you could try setting different background classes and implementing a change of class on a timer using this:
$(document).ready(function(){
var seconds = 5000; // set in milliseconds
var step = 1; // place to start
var limit = 3; //limit of background images (remember that 0 is the start so 3 is for 4 background images)
$(".global-header").addClass("banner"+step).fadeIn(1000);
setInterval(function(){
$(".global-header").fadeOut(500,function(){
$(this).removeClass("banner"+step);
step = (step > limit) ? 1 : step + 1;
$(".global-header").addClass("banner"+step).fadeIn(1000);
});
},seconds);
});
And then use different class's for the background image. (I used .banner in this instance):
.banner1{
background:url(../images/something.jpg);
}
.banner2{
background:url(../images/somethingElse.jpg);
}
.banner3{
background:url(../images/soemthingElseAgain.jpg);
}
you can experiement with the different range of J-query effects, I used fadeIn for simplicity.
Hope this helps.

change css on scroll event w/ requestAnimation Frame

I want to change the background color of in-viewport elements (using overflow: scroll)
So here was my first attempt:
http://jsfiddle.net/2YeZG/
As you see, there is a brief flicker of the previous color before the new color is painted. Others have had similar problems.
Following the HTML5 rocks instructions, I tried to introduce requestAnimationFrame to fix this problem to no avail:
http://jsfiddle.net/RETbF/
What am I doing wrong here?
Here is a simpler example showing the same problem: http://jsfiddle.net/HJ9ng/
Filed bug with Chromium here: http://code.google.com/p/chromium/issues/detail?id=151880
if it is only the background color, well why don't you just change the parent background color to red and once it scroll just change it to pink?
I change your CSS to that
#dad
{
overflow-y: scroll;
overflow-x: hidden;
width: 100px;
height: 600px;
background-color:red;
}​
I remove some of you Jquery and change it to this
dad.bind('scroll', function() {
dad.css('background-color', 'pink');
});
And I remove this line
iChild.css('backgroundColor', 'red');
But is the Red color it is important that won't work for sure http://jsfiddle.net/2YeZG/5/
I like Manuel's Solution.
But even though I don't get what you're exactly trying to do, I want to point out a few things.
In your fiddle code, I saw that you included Paul Irish's Shim for requestAnimationFrame.
But you never use it.
(It's basically a reliable setTimeOut, nothing else) it's from frame based animations.)
So since you just want to change some CSS properties, I don't see why you would need it. Even if you want transitions, you should rely on CSS transitions.
Other than that your code could look something like
dad.bind('scroll', function() {
dad.css('background-color', 'pink');
eachElemNameHere.css('background-color','randomColor');
});
Also you should ideally not use something like that if you can help it. You should just add and remove class names and add all these properties in your CSS. Makes it work faster.
Also, again I don't quite get it, but you could use the jQuery function to find out each elements' position from the top to have better control.
Your problem seems to be that you only change the background color of the elements which have already been scrolled into view. Your code expects that the browser waits for your code to handle the scroll event before the browser redraws its view. This is most probably not a guarantee given by the HTML spec. That's why it flickers.
What you should do instead is to change the elements which are going to be scrolled into view. This is related to off screen rendering or double buffering as it is called in computer games programming. You build your scene off screen and copy the finished scene to the visible frame buffer.
I modified your first JSFiddle to include a multiplier for the height of the scroll area: http://jsfiddle.net/2YeZG/13/.
dad.bind('scroll', function() {
// new: query multiplier from input field (for demonstration only) and print message
var multiplier = +($("#multiplier")[0].value);
$("#message")[0].innerHTML=(multiplier*100)-100 + "% of screen rendering";
// your original code
var newScrollY = newScrollY = dad.scrollTop();
var isForward = newScrollY > oldScrollY;
var minVal = bSearch(bots, newScrollY, true);
// new: expand covered height by the given multiplier
// multiplier = 1 is similar to your code
// multiplier = 2 would be complete off screen rendering
var newScrollYHt = newScrollY + multiplier * dadHeight;
// your original code (continued)
var maxVal;
for (maxVal = minVal; maxVal < botsLen; maxVal++) {
var nxtTopSide = tops[maxVal];
if (nxtTopSide >= newScrollYHt) {
break;
}
}
maxVal = Math.min(maxVal, botsLen);
$(dadKids.slice(minVal, maxVal)).css('background', 'pink');
});
Your code had a multiplier of 1, meaning that you update the elements which are currently visible (100% of scroll area height). If you set the multiplier to 2, you get complete off screen updates for all your elements. The browser updates enough elements to the new background color so that even a 100% scroll would show updated elements. Since the browser seldom scrolls 100% of the area in one step (depends of the operating system and the scroll method!), it may be sufficient to reduce the multiplier to e.g. 1.5 (meaning 50% off screen rendering). On my machine (Google Chrome, Mac OS X with touch pad) I cannot produce any flicker if the multiplier is 1.7 or above.
BTW: If you do something more complicated than just changing the background color, you should not do it again and again. Instead you should check whether the element has already been updated and perform the change only afterwards.

Categories