Level: beginner • Mithril.js Version: latest
animation api dom m.mount m.stream oncreate
This Mithril.js code example was taken from Mithril.js Gitter and slightly edited.
It shows random dog images requested by the Dog API and displayed with an adjustable blur effect.
The blur effect can be adjust by using a slider, that applies a value between 1 and 10 using the CanvasRenderingContext2D.filter
.
The filter is part of the Canvas API
, the JavaScript Canvas 2D API, which provides a means for drawing graphics via JavaScript and the HTML <canvas>
element.
Type | Name | URL |
---|---|---|
script | mithril@latest | https://unpkg.com/mithril@latest |
script | mithril-stream@2.0.0/stream.js | https://unpkg.com/mithril-stream@2.0.0/stream.js |
function BlurryDog({attrs: {src, blur}}) {
let el = m.stream()
let context = el.map(x => x.getContext('2d'))
let loaded = m.stream()
let image = src.map(src => {
let image = new Image()
image.src = src
image.onload = () => loaded(true)
return image
})
m.stream.merge([el, context, image, loaded, blur])
.map(([el, context, image, loaded, blur]) => {
if (!loaded) return;
requestAnimationFrame(() => {
el.width = el.width
context.filter = `blur(${blur}px)`
context.drawImage(image, 0, 0, el.width, el.height)
})
})
return {
view() {
return m('canvas', {
width: 200,
height: 200, oncreate: v => el(v.dom),
style: 'background: #DDD'
})
}
}
}
function RandomBlurryDog({attrs: {blur}}) {
let src = m.stream()
fetch('https://dog.ceo/api/breeds/image/random')
.then(x => x.json())
.then(x => src(x.message))
return {
view: () => m(BlurryDog, {src, blur})
}
}
function App() {
const blur = m.stream(5)
const count = m.stream(5)
function view() {
return m('.app',
{style: 'display: grid;'},
m('.form',
{style: 'display: grid; grid-template-columns: 1fr 3em 3em; gap: 1em;'},
m('label',
'Blur', m('input[type=range]', {
style: 'width: 100%; height: 2em;',
oninput: e => blur(e.target.valueAsNumber),
max: 10,
min: 0,
value: blur()
})
),
m('button', {onclick: () => count(count() + 1)}, '+'),
m('button', {onclick: () => count(count() - 1)}, '-')
),
m('.dogs',
Array(count()).fill(0).map(() =>
m(RandomBlurryDog, {blur})
)
)
)
}
return {view}
}
m.mount(document.body, App)
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 some Mithril.js API methods like m.stream
or m.mount
, besides Mithril.js' basic m() hyperscript function.
It is also showing the oncreate
hook, which is one of several Mithril.js' lifecycle methods.
The code sample was authored by JAForbes. It was last modified on 31 October 2021.
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.