Mosaic Animation

by mithril

Level: beginner • Mithril.js Version: latest

This example shows a mosaic effect on a picture using CSS. The effect is made by dividing, rotating, and fading out the picture (and vice versa). The example was taken from the official website at https://mithril.js.org/examples.html and slightly modified.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

JavaScript

var root = document.body

var empty = []
var full = []
for (var i = 0; i < 100; i++) full.push(i)

var cells

function view() {
	return m(".container", cells.map(function(i) {
		return m(".slice", {
			style: {
			  backgroundPosition: (i % 10 * 11) + "% " + (Math.floor(i / 10) * 11) + "%"
      },
			onbeforeremove: exit
		})
	}))
}

function exit(vnode) {
	vnode.dom.classList.add("exit")
	return new Promise(function(resolve) {
		setTimeout(resolve, 1000)
	})
}

function run() {
	cells = cells === full ? empty : full
	m.render(root, [view()])
	setTimeout(run, 2000)
}

run()

CSS

#root {
  margin:auto;
  max-width:600px;
  width:100%;
}
.slice {
  animation:enter 1s;
  animation-fill-mode:forwards;
  background-image:url(https://raw.githubusercontent.com/MithrilJS/mithril.js/master/examples/animation/flowers.jpg);
  height:60px;
  float:left;
  opacity:0;
  width:60px;
}
.slice:nth-child(10n) {
  clear:right;
}
.exit {
  animation:exit 1s;
}

@keyframes enter {
	from {
    opacity:0;
    transform:rotate(-90deg) scale(0);
  }
	to {
    opacity:1;
    transform:rotate(0) scale(1);
  }
}

@keyframes exit {
	from {
    opacity:1;
    transform:rotate(0) scale(1);
  }
	to {
    opacity:0;
    transform:rotate(90deg) scale(0);
  }
}

The snippet requires the latest version of Mithril.js framework. It is ideal for beginners showing some basic recipes.

In this example we can see an example of Mithril.js' m.render API method, besides it core m() hyperscript function. It is also showing the onbeforeremove hook, which is one of several Mithril.js' lifecycle methods.

The code sample was authored by mithril. It was last modified on 27 October 2021. Want to see more examples written by mithril? Then Click here.

Contribute

Do you see some improvements, that could be addressed here? Then let me know by opening an issue. As an alternative, you can fork the repository on GitHub, push your commits and send a pull request. To start your work, click on the edit link below. Thank you for contributing to this repo.

See more code examples  •  Edit this example on GitHub