Is it possible to change background randomly?

0 votes
asked 5 days ago by LeoSteps (350 points)
I have some background images (bg01.jpg, bg02.jpg, bg03.jpg, etc.) and I want these images to appear randomly in each passage.

Can someone help me?

1 Answer

0 votes
answered 5 days ago by TheMadExile (42,760 points)
selected 4 days ago by LeoSteps
 
Best answer

I'd start with putting something like the following in your Story JavaScript:

setup.backgrounds = [
	// Put your image paths here.
	"bg01.jpg",
	"bg02.jpg",
	"bg03.jpg",
	"etc.jpg"
];
setup.randomBackground = function () {
	$(document.body).css(
		'background-image',
		'url(' + setup.backgrounds.random() + ')'
	);
};
setup.clearBackground = function () {
	$(document.body).css('background-image', 'none');
};

Once that's done, you have a couple of choices.

 

1. If you want the backgrounds to only appear in certain passages, then you could put the following at the top of each passage:

<<run setup.randomBackground()>>\

You may clear the current background with:

<<run setup.clearBackground()>>\

 

2. On the other hand, if you want them to appear in most passages, then you'll probably want to put the following in the PassageReady special passage instead:

<<if tags().includes("nobg")>>
	<<run setup.clearBackground()>>
<<else>>
	<<run setup.randomBackground()>>
<</if>>

Then you simply tag any passage you do not wish to receive a background with nobg.

commented 4 days ago by LeoSteps (350 points)

It's work! Thanx a lot!!! yes

Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...