For some, motion blur has been a holy grail of web animation.
Over the years, many attempts have been made at applying motion blur to regular HTML content. Typically, these attempts have either been confined to SVG filters, which are typically extremely slow, limiting and of low visual fidelity. Or <canvas> elements, which look good but can't render HTML.
Well, SVG filters are still slow, but with the new HTML in canvas API, we can now render real HTML elements inside the <canvas> element.
This means we can apply all kinds of effects to elements while keeping all their styling and accessibility. Text is still selectable, screen readers still work, buttons still click.
What's more, <canvas> lets us use WebGL/GPU to render elements. Leading to visual effects that look amazing but also perform well.
In this guide, we'll look at how HTML in canvas works, how to draw and animate HTML in a canvas yourself, and talk about some of the rough patches you might not be expecting. Then we'll look at our Motion FX API, which handles all of this for you.
What is HTML in canvas?
HTML in canvas is a new API coming to browsers starting with Chrome. Broadly speaking, it lets us put normal HTML elements like <div> inside <canvas>.
These elements are laid out and styled by the browser as normal. They receive events, they can receive focus, and they're in the accessibility tree.
This is the key difference between HTML in canvas and older approaches, like html2canvas, which re-implement the browser's rendering in JavaScript with a large bundle, and only ever give you a static picture. Whereas HTML in canvas gives you a live picture of a live element rendered fully by the browser.
Browser support
HTML in canvas is new, so it's currently only supported (as of writing) in Chrome 157 and later.
This means everything you build with it needs a fallback, which we'll come back to.
To detect support, set the content attribute on a canvas and check it stuck:
const test = document.createElement("canvas")
test.setAttribute("content", "drawable")
const supportsHTMLInCanvas = test.content === "drawable"You'll find older articles and demos use a layoutsubtree attribute and a texElementImage2D() method. These are the names from the origin trial. They were changed before the final API shipped, so code that uses them won't work in Chrome.
Drawing
Let's start with drawing some HTML into a 2D canvas.
First, give the canvas content="drawable", and give each child you want to draw the drawable attribute.
<canvas content="drawable">
<div class="card" drawable>
<h2>Hello</h2>
<button>Click me</button>
</div>
</canvas>Then, draw the child in the canvas's paint event.
const canvas = document.querySelector("canvas")
const card = document.querySelector(".card")
const ctx = canvas.getContext("2d")
canvas.onpaint = () => {
ctx.reset()
ctx.drawElementImage(card, 0, 0)
}The browser fires paint once the children have their first layout, and again every time one of them changes. So when you hover the button and its background changes, paint fires and the canvas redraws. When you type into an input, paint fires.
Regular <canvas> users might be surprised that you don't need an animation loop.
Size the canvas
If you're used to the way normal elements render, one surprise might be the fact that <canvas> elements don't render sharply by default on most displays.
This is for two reasons.
First, <canvas> is the same as any other image. It has its own intrinsic resolution, which you have to set manually. It doesn't automatically know it from its layout.
Second, you might have a layout that you've measured as 100px wide and 100px tall. But that one "pixel" is displayed differently on different displays. Some use a 2x2 physical pixel grid to represent a single "pixel", some use more, and some use values in-between.
If we want our <canvas> image to be sharp, we have to account for this pixel density.
Use a ResizeObserver with the device-pixel-content-box option to make the grid match the real pixels on the screen:
new ResizeObserver(([entry]) => {
const [size] = entry.devicePixelContentBoxSize
canvas.width = size.inlineSize
canvas.height = size.blockSize
canvas.requestPaint()
}).observe(canvas, { box: "device-pixel-content-box" })Setting width or height clears the canvas, so canvas.requestPaint() asks the browser for a new paint event.
Now there's a second surprise. The positions you pass to drawElementImage() are relative to the internal canvas resolution, not CSS pixels. On a 2x screen, drawElementImage(card, 100, 0) moves the card just 50 CSS pixels.
I find the simplest way is to scale the canvas context by the device pixel ratio once, before drawing anything, and then giving the drawn size in normal CSS pixels:
canvas.onpaint = () => {
ctx.reset()
ctx.scale(devicePixelRatio, devicePixelRatio)
ctx.drawElementImage(card, 0, 0, card.offsetWidth, card.offsetHeight)
}With all this in place, your <canvas> is rendering sharply, and you can move and render elements in pixel values that make intuitive sense.
Hit detection
For elements to respond to pointer input, they need hit detection. In 2D <canvas> context, drawElementImage() automatically understands where to move the element's hit box based on where you've chosen to draw the element. This isn't the same for 3D contexts, which we'll see later.
Animating HTML in canvas
So, we want to animate our element. We've got Motion, so how hard can it be?
Let's start by animating the drawable element the same way we'd animate a normal element:
animate(card, { backgroundColor: "#f00", x: 300 })The element's background colour will change, but the element won't move.
Motion is setting the element's transform, just as it would a normal element. But, as per the spec, "rendering starts at the element's border box, before CSS transformations". So the element's own transform, translate, rotate and scale styles are never rendered.
It's actually worse than that, because they aren't ignored entirely either. A drawn element's place for hit testing should be set by a matrix that maps its border box, before its CSS transforms, into the canvas. drawElementImage() sets that matrix from where you draw it. But in my tests in Chrome 158, the element's own transform is still applied on top. So the picture stays where it was, and the clickable area wanders off somewhere else. In Chrome 157 the behaviour was slightly different, so it could be an early implementation bug.
So CSS transforms are worse than useless. What to do?
Fixing transforms on drawable elements
We could use motion values to trigger paints when they update, and use the value inside the onpaint handler:
import { animate, motionValue } from "motion"
const x = motionValue(0)
x.on("change", () => canvas.requestPaint())
canvas.onpaint = () => {
ctx.reset()
ctx.scale(devicePixelRatio, devicePixelRatio)
ctx.translate(x.get(), 0)
ctx.drawElementImage(card, 0, 0, card.offsetWidth, card.offsetHeight)
}
animate(x, 300, { type: "spring" })With this setup, the card springs 300 pixels to the right as you'd expect. Its hit area follows it every frame, so you can click the button while it moves. Every Motion option works here, from springs to keyframes to scroll-linked animations.
This setup is a little bit complicated though, and exactly the pain point that we're trying to fix with Motion FX. Instead of wrapping your content in a <canvas> we can use <motion-fx>.
A CSS transform on an element inside <motion-fx> is drawn, and Motion animations of transforms work out of the box, letting you avoid all of this setup.
3D animations with WebGPU
2D canvas is great for learning the basics, but we think the most common reason to put HTML in a canvas will be applying effects via the GPU. Blur, distortion, lighting: All of this requires shaders, and that means WebGPU.
The basic situation is that we're still responsible for wiring up paints, but with WebGPU we use different APIs and a different pipeline.
Instead of drawing into the canvas, you essentially copy the element's picture into a texture, and your shader samples it.
const adapter = await navigator.gpu.requestAdapter()
const device = await adapter.requestDevice()
const context = canvas.getContext("webgpu")
context.configure({
device,
format: navigator.gpu.getPreferredCanvasFormat(),
alphaMode: "premultiplied",
})
let texture
canvas.onpaint = () => {
const { width, height } = canvas.getElementImageDefaultSize(card)
if (!texture || texture.width !== width || texture.height !== height) {
texture?.destroy()
texture = device.createTexture({
size: [width, height],
format: "rgba8unorm",
usage:
GPUTextureUsage.TEXTURE_BINDING |
GPUTextureUsage.COPY_DST |
GPUTextureUsage.RENDER_ATTACHMENT,
})
}
device.queue.drawElementImageToTexture({ source: card }, { texture })
// Draw a quad that samples `texture`, with your own shader
render(texture)
// Tell the browser where the element is now, for hit testing
canvas.updateElementGeometry(card, {
canvasTransform: new DOMMatrix().translate(x.get(), 0),
})
}This can look like a lot, and is also something that Motion FX abstracts, but there are two key differences from 2D context.
First, textures. getElementImageDefaultSize() gives the size of the element's picture in grid pixels and you're responsible for using this to set the texture size and drawing the picture into the texture.
Second, hit detection. In 2D, the browser could see where you drew the element. In WebGPU, it can't: your shader could put the picture anywhere so you manually tell it where that is, using updateElementGeometry().
Those are the basic techniques for both 2D and 3D contexts. As you can see, there's already a lot of boilerplate and wiring which provides a lot of flexibility but likewise is a bit of a pain to write and maintain. Even for agents!
Pain points
There are more pain points, too. Motion FX handles most of them for you.
Fallback
In a browser without HTML in canvas, the children of a <canvas> are never shown. Which is a shame, because in most situations it's ideal fallback content.
The safest pattern is to start with normal HTML, outside any <canvas>. Then, only when the browser supports HTML in canvas, create the canvas and move the elements in:
if (supportsHTMLInCanvas) {
const canvas = document.createElement("canvas")
canvas.setAttribute("content", "drawable")
card.before(canvas)
card.setAttribute("drawable", "")
canvas.append(card)
}Of course, this is handled automatically with <motion-fx>. A <canvas> is only rendered if the browser supports HTML in canvas and WebGPU.
Things that aren't drawn
By default, the picture of an element is its border box and anything inside it. Anything painted outside that box is cut off: a box-shadow, an outline, a filter: drop-shadow().
To include it, give drawElementImage() a source rectangle, as you would with the existing <canvas> drawImage(). The source can reach past the border box, so start it outside the element and make it bigger by the size of the shadow on each side:
const shadow = 20
const x = 100
const y = 50
canvas.onpaint = () => {
ctx.reset()
ctx.scale(devicePixelRatio, devicePixelRatio)
const width = card.offsetWidth + shadow * 2
const height = card.offsetHeight + shadow * 2
ctx.drawElementImage(
card,
-shadow, -shadow, width, height, // Source, relative to the border box
x - shadow, y - shadow, width, height // Destination
)
}Move the draw target box back by the same amount to compensate, so the element's border box is still drawn in the right place.
Motion FX doesn't draw outside the border box either. With <motion-fx>, put the shadow inside a wrapper with some padding.
And then some things aren't drawn on purpose, for privacy. The canvas can read its own pixels, so the browser won't draw anything that could leak information about the user:
- Images and iframes from another origin, unless they're loaded with CORS.
- Visited links.
- Spelling and grammar markers.
- System colours and themes.
- Pending autofill.
So an image from a CDN without crossorigin="anonymous" is drawn blank. Add the attribute, and make sure the CDN allows cross-origin requests, and it draws as normal:
<canvas content="drawable">
<div class="card" drawable>
<!-- Drawn blank -->
<img src="https://cdn.example.com/photo.jpg" alt="A photo" />
<!-- Drawn as normal -->
<img src="https://cdn.example.com/photo.jpg" alt="A photo" crossorigin="anonymous" />
</div>
</canvas>Nested elements
A drawable element can be inside another drawable element. The browser cuts it out of its parent's picture and makes another picture just for it. This is useful as you can have nested blur effects, for example.
But the parent's transform isn't applied to the child's picture, so you have to incorporate the ancestor transforms when drawing a child.
Motion FX
Motion FX is our take on HTML in canvas. It's a WebGPU layer for your HTML, with real motion blur, lens blur and fog, built for Motion's animations.
<motion-fx>
<div class="card">Live HTML</div>
</motion-fx>import { animate } from "motion"
import { defineMotionFX, motionBlur } from "motion-plus-dom/fx"
defineMotionFX() // defines <motion-fx> element
document.querySelector("motion-fx").shaders = [motionBlur()]
animate(".card", { x: 400, rotate: 90 }, { type: "spring" })Notice this is the first thing we tried: animate() on the element itself. Motion FX handles the split between the live element and its picture for you.
How? Motion doesn't write to an element directly. It finds the element's renderer, and a normal element's renderer writes its styles. Motion FX gives each child of <motion-fx> its own renderer instead. It still writes colours and other styles, but it keeps transforms and opacity out of the style and asks the canvas for a frame. Each frame, the canvas draws the picture with the element's latest values, on top of its own CSS and its parents' transforms, and tells the browser where it is for hit testing. So animate(), gestures and motion components all move the picture, with no new API to learn.
- Animations just work.
animate(),scroll(),hover(),press()anddrag()all work on children of<motion-fx>. Motion knows the element is drawn, so it moves the picture and keeps the hit area in sync. - Layout is normal CSS. Children are laid out by grid, flex or anything else, then drawn in place.
- The fallback is built in. In browsers without HTML in canvas or WebGPU, the children are normal DOM and still animate. Only the effects are missing.
In React, we also have the FX component. motion components inside it, with all their gestures, layout animations and exit animations, work as normal:
import { motion } from "motion/react"
import { FX, motionBlur } from "motion-plus/fx"
<FX shaders={[motionBlur()]}>
<motion.div
className="card"
animate={{ x: 400 }}
transition={{ type: "spring" }}
/>
</FX>By default, direct children of FX are given the drawable attribute, but we can pass fx to deeper motion components to also apply effects to them separately.
Motion blur
Motion blur was the first shader we built for Motion FX.
Previous attempts at motion blur via SVG filters tend to take the current element position and blur along x or y axis.
This isn't real motion blur. It leads to an effect where the box appears ahead of its current position rather than trailing behind it.

Motion FX blends the element along the path it really took, from where it was last frame to where it is now. So the blur trails the element and ends at its true position.
That means a spin blurs more at the edges than the centre, a scale blurs outwards, and a fast spring blurs more than a slow one. It blends up to 24 poses of each element in a frame. An element that doesn't move is drawn once, sharp.

See this live in action (in supported browsers):
Lens blur and fog
Give <motion-fx> a CSS perspective and move children in z, and they're placed in real 3D space. lensBlur() blurs them by their distance from a focal plane, like a camera lens. Animate focus for a rack focus effect:
const focus = motionValue(0)
fx.shaders = [lensBlur({ blur: 3, focus })]
animate(focus, -400, { duration: 1.2 })fog() fades distant children to a solid colour, like a 90s 3D game. Unlike opacity, the far children stay solid, so nothing behind them shows through. This allows for a softer, calmer fade out than using opacity.
Every numeric option, and fog's colour, accepts a motion value, so the effects animate like anything else in Motion.
FAQs
- Is HTML in canvas accessible?
Yes. Drawn elements stay in the accessibility tree with their roles, labels and focus order, and focus rings and text carets are drawn too. You still need to make sure what you draw matches what the HTML says.
- Can I use HTML in canvas in production?
Yes, with a fallback. It's on by default in Chrome 157 and later, but not yet in Safari or Firefox. Start with normal HTML and only move it into a canvas when the browser supports it. Motion FX does this for you.
- Why doesn't my CSS transform show up in the canvas?
The canvas draws an element from its border box, before its own CSS transforms. Place the element with the draw call in 2D, or in your shader in WebGL and WebGPU, and call
updateElementGeometry()so its hit area follows. Transforms on elements inside the drawn element are drawn as normal.- Does HTML in canvas work with WebGL?
Yes. Use
texElementSubImage2D()to copy an element into a WebGL texture. As with WebGPU, callupdateElementGeometry()so the element receives clicks where you drew it.