简体   繁体   中英

Random Background Image For Background Clip

On my personal site: http://pavelrozman.com/ the background photo reloads on every refresh with some javascript. Then, I stumbled upon a cool clipping mask tutorial on the web.

h1 {
font-family: Arial;
font-size: 5em;
text-align: center;

background-image: url(Galaxy.jpg);

-webkit-background-clip: text;
background-clip: text;

color: rgba(0,0,0,0);

}

I want to use a random image where it says 'Galaxy.jpg' so that ever refresh there's a new image that is clipped over the text.

This is how I would approach the problem, the only solution I can think of will require use of jquery to change the background image.

First I would create an array of the image names that you want to cycle for your backgrounds. I called this variable background.

Jquery Code:

   var background = ["Galaxy","Galaxy2","Galaxy3","Galaxy4","Galaxy5"];
   var randombackground = Math.floor((Math.random()*5)); 
   /*This will generate a random number between 0 and 4, which we will use to access our array, change the 5 to the number of wallpapers that you have*/


$(document).ready(function(){
   $("h1").css("background-image","url('" + background[randombackground] + ".jpg')");
});

The code above will generate a random number which will select a different wallpaper every time the page loads. This is because the random number will change every time the page is loaded. Please note that you will need to have http://jquery.com/ installed for the code to work correctly.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM