Background color changing tiles

This is more of a theoretical question with a few code snipets. I'd like to create a website with a background full of tiles that change constantly in color and shape. A good example are the Windows Phone 8 tiles. Of course later I'd like to create a more complex effect, but I'd like to know how you would go about changing every 50x50px square individualy, for example.

This is a code snipet for changing the background color constantly.

.animate {
    height: 200px;
    width: 400px;
    border: 1px solid #000;
    -webkit-animation: animate_bg 5s;
    animation: animate_bg 5s;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
}

@keyframes animate_bg {
    0%   {background:red;}
    50%  {background:green;}
    100% {background:blue;}
}

@keyframes animate_bg {
    0%   {background:red;}
    50%  {background:green;}
    100% {background:blue;}
}

@-webkit-keyframes animate_bg {
    0%   {background:red;}
    50%  {background:green;}
    100% {background:blue;}
}

Now do I need to create this effect again and again and again until it fills up my page, or is there a better way of doing so? Maybe there's a 'random repeat' function similar to bg-repeat? Note: Tiles should be randomized in starting color.

Thank you!


There is certainly a better way (as there usually is when you find yourself repeating code).

Use CSS transitions for the animation effect, define a lot of classes - each for a different color, and randomly assign them with JavaScript.

Here's a simple example showing what I wrote above in action. It supports unlimited number of tiles and colors.

var tiles = document.getElementsByClassName('tile');
var totalTypes = 5;
var interval = 1000;

function paintTiles() {
  for (var i = 0; i < tiles.length; i++) {
    tiles[i].className = 'tile'; // reset classes
    tiles[i].classList.add('type' + Math.ceil(Math.random() * totalTypes));
  }
}
paintTiles(); // initial paint
setInterval(paintTiles, interval); // paint afterwards
.tile {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: 1px solid black;
  transition: 1s all linear;
}

.type1 {
  background: red;
}

.type2 {
  background: blue;
}

.type3 {
  background: green;
}

.type4 {
  background: yellow;
}

.type5 {
  background: chucknorris; 
  /*  
  :)
  inspired by: http://stackoverflow.com/questions/8318911/why-does-html-think-chucknorris-is-a-color
  */
}
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<br>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
链接地址: http://www.djcxy.com/p/87366.html

上一篇: 如何创建一个像链接一样的HTML按钮?

下一篇: 背景颜色变化瓷砖