Bringing Spiders to the Web with RequestAnimationFrame
Animating on the web has never been easier. But what if you want to make life difficult for yourself? In this introduction to requestAnimationFrame, we’ll throw away the conveniences of modern life and learn how to build frame-based animations from the ground up. There will be cursor effects, spring physics, and, as if live demos aren't scary enough, we'll put an itsy-bitsy spider on the world wide web.
Duncan Petrie
Duncan Petrie is a London-based software engineer, writer, and artist from Milwaukee, Wisconsin.
Links
Video Permalink ¶
Transcript
Yeah, so I'm gonna talk about animation today. I like animation a lot, and as I'll get into, there are a lot of ways to do it, maybe smartly, but I'm gonna talk about ways to not do that.
Yeah, and requesting it, so let's just, yeah, get into it.
Maybe you have seen, this is the first website. It looks like this, it was created in 1989, '91, something like that, and you can still go to it today. It still looks like this, pretty cool. One thing you might notice is that you're bored. There's nothing there, nothing going on. You think I'm gonna read all that? It's 2026, there are no pictures, there are no colors. We can do better, so, oh yeah, I just wanted to also show, you know, this is what it looks like, you can go that URL.
You all probably know that. Great, so the first thing maybe we can do to improve this website, we like centered text, so let's bring this stuff over here. Everything else, you know, no one's gonna read that, so we'll get rid of it. We can also use, you know, something like Inter, right? It's the only font that we're allowed to use now, so let's use that. Add some nice gradients, right?
Or if we're coming into the future, right? You know, white backgrounds are very last year, we can't have that anymore. Maybe add, you know, Navbar, some pills that all say the same thing. Every website needs these little cards with the border, of course, so we'll do that. Great, so we're making great strides. The other things that we need to pay attention to when we're approving a website is our audience, our demographics.
And when you're building a website, there are two people, two groups of people you need to keep in mind. One are the venture capitalists, and two are the iPad kids. So for the venture capitalists, we can add some maybe more friendly language for them. And for the iPad kids, maybe referring, if someone's viewing this as an iPad on an iPhone Duo, also would be great.
We can add subway surfers on the side. Perfect, much, much improved. And then we can give ourselves an award also, just 'cause we've done such a good job. Obviously not, that was horrible, right? I think improving websites, making them pleasing and elegant has a lot to do with subtlety and elegance, grace, right? These little touches where you put extra care into the things that you're building and that is reflected in how people use them and enjoy them and et cetera.
And one of the ways that I think, right, little subtle enhancements can be made are through animation. Like I alluded to before in this modern world, there are a lot of great ways to make performant, accessible, responsible animations. You can do a lot with just plain CSS transitions. There are keyframes. You can do something like a little spin, like you just saw there. The web animations API too.
I learned about this for this talk, but it's really great. It's essentially a way to sort of programmatically create keyframes. Very easy to use. You can write sort of like CSS inline in there. You can play them and pause them, that's lovely. And for anything more complicated, there are of course a load of great third party libraries that you can use to do more complicated things.
But what if you want something different? What if you want to throw all that away? What if you're an innovator? What if you're a disruptor? What if you're not like other girls? What if you want to do things the hard way? CSS, see, is for babies. Keyframes are for people who don't know how to tie their own shoes. The Web Animations API is what, five years old and you wouldn't trust a five year old to drive your car.
I've got motion sickness. GSAP is for SAPs and animate.js is a cool landing page and we hate cool landing pages, so we can't use that. Where do you turn when you're all out of friends? What do you do when you've got nothing left? This is where requestAnimationFrame comes in. So, just a super brief, requestAnimationFrame is a JavaScript API that lets you hook into the browser's rendering cycle. So you can, all of the things that you can do with CSS, all the things that you can do with Web Animations API, you can basically create those yourselves using this and I think it's a good way to understand how those abstractions work under the hood.
We'll get into that, but let's start with a quick example. So, let's say that we have a box. It's a nice box, I don't know. We wanna get it to the other side of the screen because that's where our house is. We're moving house and yeah, we need to get our box over here, right? And we need to be especially careful because inside of this box is our prized Faberge egg. I don't know, it's very fragile.
So, a naive, if we're gonna use JavaScript, if we're gonna try and figure out how to do this ourselves, essentially, to understand how the underlying systems work. A naive implementation might be just to calculate the distance there between our new house and our old house and then just translate it over. So, updating the CSS there to be the distance. And if we do that, well, we can see our egg's broken. We need to animate it slowly over time, right?
So, how do we do that? Well, how about a function? Yeah, that moves our egg slowly. So, maybe what we'll do is we'll have an X position, and then every time the function gets called, we just increment X by a little bit and update the CSS. So, every time this gets called, you can see it's slowly moving over. But this gets a little inefficient. We don't wanna just call this a bunch of times.
We need to find a way to call this often. You might be thinking, well, let's use a while loop. This is not good because, as you can see up there, we're in the millions and billions, I don't know how many digits there are there. But a while loop will run way too much. And as you can see, our computer is overheating and our house is on fire. I don't know how relevant this is to this, but it flies in the face of our insurance fraud plans, which is we need to move our egg out of our house first and then burn it to whatever, I don't know.
Yeah, so we need to figure out how to do this. Before requestAnimationFrame, there's a thing called setInterval, which takes a function similar to setTimeout, also does this. So you'll put a function in here, something like, right, our move egg, and then the second parameter there is the delay. So what I'm saying here is that every millisecond, this function should be called again.
There are a lot of problems with setInterval though. For rendering-based things like this, the browser throttles it, so you can see it's not actually getting called once per millisecond. It's also like, it will keep running when you move to another tab, which means that if someone has your website up, right, and they're doing other things, it's gonna drain their battery, especially if you're doing complicated animation work.
So in order to solve this, this is what requestAnimationFrame was created for, was basically a replacement for setInterval, a way to call code every so often, as much as it can, basically, be called, but responsibly. So this was the first evidence I could find. Paul Irish's blog talked about this in 2011, a proposal. You can tell it was 2011 because he says, "Yeah, bro, totes my goats," on it, which I thought was very charming.
And yeah, you can see, here's the MDN, it's been baseline since 2015, and I was trying to get in the heads of the people, 'cause obviously I wasn't born then, get in the heads of what it was like in 2015 when this miracle came to be. And I was doing some 2015 research, right? This meme is also from 2015, where, well, if you can see the whole thing, there we go, friendship ended with Muda, Cyr, and now Salman is my best friend, right, great.
So I was thinking, what would people who are really in the know about RequestAnimationFrame be thinking? So this is an artist's rendition of what people were probably creating at the time. I can't verify this, but I can assume. So yeah, so let's try and use Request, oh, and then also, I just wanna say, any animation library you have used is using RequestAnimationFrame under the hood. These are just the three examples that I showed before.
But yeah, this is the low-level way that people create complicated animations. So let's figure out how to use it. How it works is it's just a function that you call. It's a standard browser API, and you pass a function into it. And when you call RequestAnimationFrame, it will queue that function to be run the next time the browser finds it convenient. So normally how this works is the browser will re-render the page every so often.
Normally it's if your device is rendering at 60 frames per second, if that's your refresh rate, then RequestAnimationFrame will let you call a function up to 60 times per second. So the browser keeps a list of all of the functions that have been called with this. And then before it repaints the page, it will just go through and say, oh, I need to call these things and update whatever, and then it will do that.
So it's a way to sort of like queue some work to be done with regards to how the website looks. So if we, oh yeah, I can show you this in here.
If I go in here, you can see every time I call this once, it's logging, but only once if there's no loop happening. What we need, of course, is something to be happening over time. So how we would do this is then we would just sort of recursively call requestAnimationFrame inside of our animate function. And we can now see, because my laptop isn't connected to the battery, it's, the refresh rate is 30 hertz or 30 frames per second or whatever.
So we can see every second this is getting logged 30 times. Cool, great, so let's move our egg. Go in here, and yeah, let's just update our function to add to X again. But then also we will loop this through with requestAnimationFrame. So when I do this, I'm also gonna add a sort of velocity so that I can update this. And now, when I call requestAnimationFrame, I'm essentially starting the loop here, and then every time it gets called at the end, it will queue another frame.
And so every frame I'm increasing it by this number. So we can see, if I have it negative, it will go backwards. If I have positive, it will go forwards. And then also, I'm just adding a maximum value here. So the max is just the distance we want to travel. So when we reach that, I guess because of the aspect ratio, it's kind of off. But when we reach that, then we'll stop. The last thing we can do here just to be responsible, because remember, even when we reach that point, it's still looping.
If our animation is done, we don't want to keep calling our function over and over again. So I'm just going to only queue another frame when we haven't reached our target yet, essentially. So we can test this. If we go forward, we hit that point. If I try and go back, we're not going back. The animation is over. So we've cleaned up everything.
We're done, great. And now that we've moved our egg to our new house, we can unpack it and look at what we've got. Essentially, the principle here, the most basic principle is we have a frame function, an animation function, which I'm calling moveEgg. And every time that function is called, we update some value. Here, I have sort of a current value and a target value. So the current value is where the egg is.
Looks like we're getting our insurance money.
We have our current value, which is X, and we have our target value, which is the max here in this case. And so we're just interpolating. We're updating our current value towards our target value, and then we're updating the display of the things. I'm just using, right, with the CSS egg.style. And then if we need to, let's call another frame. So that's sort of the basics. And let's do something more complicated now.
Let me go back in here.
So all well and good. You can see how that previous example, like you could very easily have done that in CSS. We're not really breaking the-- we're not pushing the boundaries of what it means to be alive. What if we want to do something more complicated? What about a cursor animation, where our egg follows us everywhere we go, and we don't have to worry about moving house and setting fire to-- like, it will just always be with us, and we don't have to worry about it breaking.
So let's create a little cursor animation where the egg will follow around our mouse. So I'll create an image in here, and then fix the position. I'm just fixing it to the top left. You can do this in a lot of different ways. And then I'm going to hook into the mouse move event. So right now, just sort of naively, every time my mouse moves, I'm updating the position of the egg. Similar to setInterval, this isn't great.
Updating the display of things within an event listener, especially like a mouse event, can be dangerous, because this will get called as much as your mouse moves. And on some devices, that is a lot. So we want to be a little more responsible. We want to use requestAnimationFrame. So what I'm going to do is I'm going to track, similar to how we had x before, like a current value, I'm going to track the current position of the egg in pos up here.
And then every time my mouse moves, I'm going to set it. And then we'll have a separate function down below, which will actually update the position of the egg. So if I call this, it's going over. And if we then wrap it in requestAnimationFrame, then we can see it's following our cursor around. Lovely stuff. A couple other things I want to do just- I make a lot of cursor animations just because I think it's fun.
And so I just want to go over quickly my framework for doing it, the best practices. So I like it to be over things. It's the biggest number I could think of is two, so put it on top of everything else. But now that it's on top of things, what you'll notice, if I try and drag, like if I try and select this text, my mouse is actually selecting the egg because it's on top. And we don't want that, we want our egg to stay faithfully by our side.
So I'll disable pointer events, make it not selectable, and also, just for overkill, draggable false. I don't know if all of those things are necessary all of the time, but I don't know, I feel like there's no harm in doing that. So now we can select text, it will never get in the way of anything. And this is especially good when I update the position to be centered on the cursor. I think this is maybe a nicer way to do it.
So I'm just adding or subtracting 50% in the translate, right? So now it's right over our mouse. And then finally, a bit of cleanup. I also like to keep this stuff in the CSS rather than having these big, long translation strings in JavaScript. So I'm going to use CSS variables. Egg.style.setProperty, and then I'll have an x and a y. Make sure to include default values there, just so if the mouse-- if I reload the page- I know we're getting out there.
If I reload the page, currently it's loading up in the top left if my mouse hasn't moved. So I could also set that to negative whatever big number, so it's not showed until I move my mouse. Just something to consider with these interaction-based animations. Great, OK. And then the last thing I think- I don't quite remember the order of the slides. I think the last thing is we also have to consider the WCAGlet.
The WCAG is the Web Content Accessibility Guidelines. Very important to think about accessibility and the different users that might be using our websites. They say you can't meet WCAG without breaking a few eggs. That's where the-- I don't know. It's a stupid joke. But I liked doing the Photoshop. So when we're building these animations that can be a little dizzying sometimes, like having a big egg following you around everywhere you go is maybe not great for people who might get dizzy or- right, we want to be respectful.
And there is a media query called prefers-reduce-motion that's particularly relevant here. I'm sure a lot of you have heard of this. And based on your use case, you can figure out what the best way to respect this is for you. For me, I'm just going to say, when the user has prefers-reduce-motion, I'm just going to get rid of my egg. And maybe it's not super necessary. And we don't have to worry about that too much. So I'm going to show you-- actually, I didn't know about this until this talk.
So maybe it will help one of you. If you're in-- I'm in Chrome right now. If you do Command-Shift-P, there are a bunch of different commands you can run. Can I make this bigger? Is that helpful? So if I search for motion, I can turn on prefers-reduce-motion. And now you can see when I move my mouse around, the egg is gone. And if I turn it back on, our egg is back. I've also-- these little panes are draggable. And there's a nice little interpolation, a nice little animation here to slow it down and speed it up.
And it also, when I press down to grab it, it gets a little bigger. So because this is sort of like an opt-in animation, essentially, what I'm going to do when I turn on prefers-reduce-motion, I'm still going to make it draggable. So I'm still using request-animation-frame for this. I'm still-- there is an animation happening. It's just maybe less woozy-ing. I don't know what the word would be. But essentially, what I'm trying to say is, whatever your use case is, just sort of try and figure out what is necessary and what is sort of for flair or for what is optional.
All right, so I'm going to turn that back off because I want to see my egg now. Great, cool. So now, this is all well and good. Our egg is following us around. But we can, similar to those little draggable panes, like let's do something like that. Let's make it a little more animated. Because right now, again, we could do this without request-animation-frame. We were doing it before. So why don't we start with having a target and a current?
So this is sort of similar to before. We had our current position, and then we had our max, our new house. When we got there, we want to stop the animation. So here, I have my target position, which is where the mouse is, and then my current position, which is where the egg is. And every frame, we want to move our egg from its current position to its target, which is the cursor. So let's set that up then. I have now a velocity, like similar to what I had in the last example. And then just every frame, I'm updating the current position to be a little closer.
This obviously won't work entirely. It's just going in one direction. But we can see it's moving. So let's now interpolate it towards our target. This is also pretty naive, because it's not working with negatives. Essentially, if our mouse is to the bottom or right, it will approach it. But then because we're using math.min, if I go to the left or above it, it's going to get sort of clamped. So then we can do some more math here that you don't want to try and understand.
A lot of absolute values to basically make it so that the egg will follow us wherever we go, and not just down and to the right. We can also see there's a problem where it sort of snaps to the axis because it's not traveling at an angle. It's traveling at both at the same time, sort of. So we can use some trigonometry to then figure out the distance and go there. And now it's clipping off the screen because you can figure this out yourself and maybe you don't want to. There are better ways to do this.
I'm just sort of showing an example. So now if we go at an angle, if we go around, it will follow us wherever we go. I'll leave that as an exercise to the reader, perhaps. But there is a way that I like to do this a lot more, a better way, which is how I did those little grabbable figures before. And that is something that I was inspired to create by Zeno's paradox. This is something that my orchestra teacher taught me about, told me about when I was, I don't know, 12, and I remembered it. I don't know why it was my orchestra teacher who told me about this.
But Zeno was a Greek in the olden times. And he had this paradox that if I was going towards the wall, I would have to get halfway to the wall first. And then I would have to get halfway to the wall again. And then I'd have to get halfway to the wall again. And what he said was that, OK, you're never going to reach the wall because you've got to do too many things. I don't understand that part. But the principle of going halfway and then halfway again and then halfway again is a very pleasing-- also, I really love this little diagram.
I like just leaping. I think Wikipedia is great. It's a nice way to simulate-- have a nice interpolation of motion. I was searching for a figure of interpolation. And I found this-- I think it's a YouTube thumbnail on Google Images. I don't know. I just liked it. So I put it in. And this is how we do that. So essentially, I'm finding the distance between-- so if I'm going to the wall, it's the distance between me and the wall, target x minus current x. And then I'm multiplying that by a half.
So that's halfway of the distance that I want to go. And I'm adding that to my current. So essentially, what this means is that every frame, I'm going halfway to my mouse. And because it's-- after this is happening at 30 frames per second, it's pretty quick. You can see if I really jolt across. It does have sort of-- it's essentially faster the further away it is. And it slows down as it gets closer, right? So let's show this-- foreshadowing.
Let's slow this down. So if I have a half, right? I'm getting halfway every frame. Maybe instead, we want to go like 5% every frame. We can see this is what that looks like. So it starts pretty fast. And as it approaches the cursor, it gets slower and slower and slower. And maybe according to Zeno, it will never reach my cursor. But that's OK. I can still reach out and grasp my Fabergé end.
And that's all I want in life. So lovely. But you might be thinking, there's an elephant in the room. There's an elephant in the room. I just found some cartoons about elephants in the room. I liked this one in particular. It's time we talked about the coral in the room. I don't know. But there is an elephant in the room, which is our frames per second. So you might be thinking, if requestAnimationFrame gets called every frame, and I'm right here with my laptop that's not plugged in, it's going at 30 frames per second.
If I plug in my laptop, it's going to go up to 60. Also, phones will run at different refresh rates, different monitors will run at different refresh rates. And essentially, what that means is that my animation is going to be moving. My egg is going to be moving at a different speed, depending on the device, which feels a little sloppy. I'll show you. So I built this little lever. I found a GIF from The Simpsons, and I turned it into a little input. So if I move this down, then we go down, and the frames per second gets capped, essentially.
I'm doing this artificially, but it has the same effect. So when I'm at 30 frames per second, it's going fairly smooth, fairly quickly. You can sort of time that in your head. If we go down to six frames per second, it's taking a lot longer to get across. And we want to sort of standardize that. So lucky for us, RequestAnimationFrame has a little gift for us, which is that it tells us the time of day. It tells us the time that the frame was called. So I have stupid names for all of these variables. But essentially, if your function inside of RequestAnimationFrame, your callback, will take an extra parameter-- I'm calling it the glaring now.
You could call it timestamp or whatever. And it's essentially the time since the page loaded. So right now, you can see it's 627,000, roughly, and it's in milliseconds. So what's that, 10 minutes, something like that? And we can use this to calculate the time since the last frame and get sort of a delta that then we can use to figure out how far we have to travel, how much of the animation should be complete, et cetera. So let's calculate that. I'm storing the previous frame and the current frame, and then I just do a little subtraction. And so now we can see the march of progress is about 200 milliseconds.
And if we're going at six frames per second, does that line up with our expectations? I don't know. If we go up to 30 frames per second, then every 33 milliseconds, it's getting called. You can do the math in your head whether that checks out. I think it does, but a long day. I think that makes sense, though. So yeah, so great. So we can use this then to figure out how much of the distance between our egg and our cursor we should actually move. So instead of having a lerp value, I'm going to call this like a half-life value because it's essentially the amount of time.
What I want is to define the amount of time in milliseconds that the egg should take to get halfway. And that works because wherever you are, wherever I am from here on the wall, if I'm here, it should take me 100 milliseconds to get here, and then it should also take me 100 milliseconds to get here and then here, and it will have that nice frame, that nice sort of slowdown as I get closer. And then I'm just going to down here calculate the half-life lerp. Not to be confused with half-life lerp, I found these pictures of people dressed up as half-life characters, which I liked. So the half-life lerp is what we're multiplying by.
So instead of using just a half, we're calculating the amount of time that has elapsed, basically. So right now, it's set to 100 milliseconds. If we speed it up or slow it down one millisecond, we can see one, two, three, four, five. It's sort of traveling about halfway every second, right? And if we speed it up by a bunch, oh, so we ran into a problem. Our half-life was too small, or this would also happen if we crank the lever down and our FPS was really low. Our lerp value over here is greater than one, which essentially means that we've overshot our target. So let's just add another clamp in here using math.min.
And now the value, as you can see here, is clamped to one. So it's always, just because too much time has elapsed from the last frame, we're just going to go right to our target. Whereas if I slow it down again, right there we go, great. So this is lovely. But I don't know, I have this segue that I think is a little goofy, I don't know. I'm not in the mindset to do it, but I'm going to, whatever. I don't know, like it's autumn right now, but I'm thinking of another season. There's something missing in my step. There's something, this, it's nice, but it's just, it's missing a bounce.
It's missing something. I don't know, there's just something missing. The backstory of Slinky's also, you should go to the Wikipedia page. I'm not going to go in it now, but it's kind of interesting. It involves a Bible translation cult in Bolivia, I think. Yeah. Anyway, I think it's time, I think it's time for something new. I think it's time for, oh shoot, it didn't work, no. There we go. Time for act two, springtime.
Let me do that again, did that work? Maybe it's a problem with my, there we go. Yeah, lovely. Okay. It's time to figure out how to make springs. I should take a drink of water. But this is my spring chicken, this is a chicken that I drew and I would like to make him spring. Here he is in his natural habitat. As you know, chickens want to cross the road, so this chicken, we need to help him cross the road.
And we can use animation to do this. So I'm just going to create a little abstraction here. I'm calling it a lerper because the previous thing we were doing was, I'm calling it lerping, linearly interpolating from one point to another. And this is, right, we have our delta. I'm creating a little step function, so every time request animation frame is called, we can call step with the time that has passed and then update our current based on the target. So this is what we just implemented, right? It works, it's great. If I hook it up here, here's just an example of how you would use that.
So when I click, I'll update the target position, and then in my request animation frame loop, I'll just calculate the delta, the time that has passed, and then step it, and then update our elements, CSS properties, whatever. So as you can see, if I go over here, if I click across, it will move. Lovely, but it's not springing. So I'm sure all of you lately have been missing GCSE physics, today's your lucky day, we're going to get back to that. And let's learn about, don't worry, it's not super complicated. I was using MathML for this, I figured it out for the first time. A pain to do, it's very verbose.
Every character needs a different element, like an equal sign gets wrapped in an HTML element and then each variable does too. I guess it's not meant to be written by hand, but I did. Anyway, this is the spring force. So in physics, if you have a spring, I don't know why I'm looking for a spring. If you have a spring, it has sort of a resting position, right? So when you leave a spring, just to, maybe you leave it, note for next time, if you leave a spring right next to the presenter, it would be at rest. If you then stretch it, it's, and that's called, physicists or anyone else would refer to that as equilibrium.
If you stretch a spring, it will be a distance away from equilibrium. So if my spring is like here normally, if I stretch it out, then if I'm like doubling the length of the spring, then the distance from the current position essentially to equilibrium, that distance is x here. And so this formula says that the spring force, which is the force that the spring is exerting towards equilibrium, is directly related to x, which is the distance out of equilibrium, and then k, which doesn't stand for anything. It's the spring coefficient. There's nothing that starts with k that is relevant. Stiffness is often what people will refer to it as, k stiffness, I don't know.
And so we'll create a little spring class over here, similar to what we did before, and create stiffness, and then we can, like I said, calculate the spring force by multiplying the stiffness by the distance between the target and the current. So if you think about maybe the mouse position as a spring, equilibrium is where the egg or the chicken, which came first, the egg or the chicken, is right on top of the cursor. And then if we are away from equilibrium, that's when maybe the egg is on the other side of the screen and it needs to come over. So in order to get the distance out of equilibrium, we just get the difference between the target and the current values, right? And then we know, as per our friend Sir Isaac Newton, that force is equal to mass times acceleration.
Very good. We can just flip this around and calculate our acceleration by dividing our spring force by a mass. And again, this is just sort of an arbitrary value. It's just a parameter we can change to change the way that the spring animates. I'm just setting them to one for now, but we'll talk about that more later. We also know that acceleration and velocity and position are related. So we can calculate the velocity by just multiplying the acceleration by time. And we've got the time, we've got the delta. So we'll multiply the velocity, or we'll multiply the acceleration right there by the amount of time that has passed since the previous frame and add that to the velocity.
We're tracking the velocity because a thing will be in motion. And a spring will essentially go back and forth because when it reaches equilibrium, it's still moving. So we need to make sure that we're tracking the speed so that it carries over and then comes back and then carries over and comes back. And then finally, of course, similar to velocity and acceleration, position and velocity are related by time, so we can update our current position then using the velocity, great. And does this work? If I click in the middle of the screen, we can see our chicken is now going back and forth.
And this is great, it is a spring, and we implemented it in the way that it works in real life, which I think is pretty cool, it's four lines of code, and this is almost the same as how springs work. You will see that our chicken is going to get tired because there's no friction, it's not slowing down, most springs will slow down, and this one isn't, and that's because we haven't accounted for something called damping. Damping is essentially the friction of a spring, it's how, the reason that a spring just doesn't bounce forever is because there's also a damping force, and this is something that's like inherent in the metal of the spring, or whatever material, so if you make a spring out of different kinds of metal, it will have a different damping coefficient, is what that's called.
And we can calculate the damping force, it's a product of the velocity, so we have that damping coefficient, whatever it is, based on the material, and if something is moving really really fast, the velocity is really high, then it's going to want to be slowed down a lot more, but if it's moving more slowly, it's going to slow down more slowly, which is intuitive, I think. So we'll add another, a third and final little variable up there called damping, and we'll calculate the damping force here, which, like I said, is just that value times our velocity, and then forces are additive, so we can just, because we know that the damping force will be pushing against the motion of the spring, and the spring force is what's moving it, so they're in conflict, so we'll just subtract the two and use that as our total force here. And now, when I spring over, my chicken will run, and the damping part will slow it down, so it'll settle on the other side, and then slow down, and then that, maybe. There you go. Ta-da! Lovely. And then also, just because we're trying to be a good physicist, we're going to use better units, so most of these equations use seconds.
I think the numbers up here are a lot more easy to read if we're using seconds instead of milliseconds, so I'm just going to do that there. And then, I'll also have these sliders to show sort of what this means. So right now, I think this is a pretty springy feeling motion, a stiffness of around 100, a mass of around 1 or 2, and a damping of around 10 or 20, so there's like an order of magnitude difference there. And we can play around with these, so like for example, if our mass is really high, it's going to get a lot more momentum essentially is what that will feel like. So it will spring for longer because it's heavier and it takes longer to slow down. So there are these principles like you can get a spring in real life and do it, and spring it around, and you can simulate the exact mass. It feels like it should be more complicated than that, which is kind of fun. And then also, maybe I won't go through this code, but another thing that you can do is when you're tracking these values like position or velocity, you can also do other things with that. So because we know the position, we can use that to scale. So if we want to go towards the horizon, we can scale the chicken in and out. And it's just some simple math that we do. I mean, it doesn't look simple because I wrote it, but it is just the closer we get to the horizon, the smaller our chicken gets, right? Great. So here we are, we have our nice little chicken, it can run up and down the road, it can cross the road. And then I also added this button to lay an egg. So now we have as many Faberge eggs as our heart desires. And if we lose some to insurance fraud, that's okay. Lovely. All right, I'm going to show just another quick example of springs. I think this is more intuitive. This is a box that I set to just follow the cursor. And I have these little, I really want to talk, I'm really, really proud of these. So it actually might have been better to show back here. Do you see that when they spring over like the input bit like wiggles a little bit and how I did that is I just have two different springs. So I'm springing the range towards the middle of the screen and then I'm also tracking a second spring value which is the little input thing in the middle, I don't know what that's called, the thumb?
Yeah, the thumb. And then I do some horrible tricks to move the thumb like as the range is moving across, to move it based on where it should be because the spring of the thumb, I've made the damping like a little lower and the mass a little higher or something so they don't move at quite the same speed and you just get that really nice subtle, again very subtle, right? Like you might not notice it if you weren't looking at it but I don't know, this is maybe the most fun that I had doing this whole presentation which says something. But great, so we have this box, as you can see if I, ooh, a little too high, you should maybe, if you're going to do this, include some limits on what you do. If I make the mass really high, as you can see it takes a little while to get up to speed but then it will overshoot because it's got this momentum, right? And if the mass is lower, it will be more quick. If my stiffness is very low, it will move much closer to like a linear speed. If my stiffness is really high, it looks like a really stiff spring, like it just, I don't know, cool. Another thing, I was talking about having, updating different display properties, like the scale of the chicken for example, based on the things that we're already calculating. So another thing we can do is we can change the rotation.
I don't know what to call this value, so I just called it rotatiness. But you can see like if we have a box that's square and we're moving it up and down, it makes sense that it's not rotating, or side to side. But what if we're moving it at an angle? What if we just rotate, can you even see that? I don't know. If we rotate it a little bit as we move, it just feels a little more like it's being pulled along with us. And you have to use your judgment in your eye to figure out exactly what's the correct amount of subtlety, and what feels good but isn't too distracting and over the top. But I wanted to show another example of how you can, because again this is just one more, I added another CSS property, and then I calculate it every frame, and I pass it in, and it took me five minutes to do this, but I don't know, I think it adds a lot. Also, I'll mention on springs, Josh Comeau, he does other things, but he has a great blog too, has a really lovely article on springs, I use this, a couple other resources too, but it has some nice little interactive examples, they have nice faces, and he talks about the frictionless world, which is this place over here, and then also, I will say again, request animation frame is not something you should be using, maybe ever, there are so many other ways, like better ways to do a lot of these things, with the cursor animations I think it makes sense, but for example, with the inputs, you can in CSS pretty easily do this thing, so easing wizard is something that I used, it will generate CSS transition functions, I don't know exactly what you would call them, but like, what it looks like is it's the word linear and then in parentheses it's a bunch of values that you couldn't really ever write by hand, and it will pretty easily make something look like a spring, so I've used that in this talk, like when putting it together quite a bit for things that I maybe said were animated with request animation frame, actually I was using this under the hood, so I would recommend like trying to find alternatives before you write everything yourself, I think that's a good thing to do.
Another example, a little cursor animation, so this is, this glyph is called a manicule, again I learned this for this talk, not to be confused with a manacle or a manicure, I like Wikipedia, a manicule, it originated in the 13-1400s on illustrated manuscripts, they would, if there was something that they thought was fun or interesting or of note, they would draw a little finger pointing to the information, and I think that is nice. So I like this glyph, and I thought, you know, why don't I have it follow my cursor around, if I hold down the mouse and drag across, maybe it will, you know, come and stay there and then shoot over, I don't know, it's just, there's a lot of little playful things you can do, do you see that, I think there might be a bug in my code. I think it might be time for Act 3, a World Wide Web.
So these are my spiders, I like them a lot, I've been working on them for a little bit, and I think this is a more complicated example of what you can do with these frame-based animations. I'm sorry for any of you that thought Halloween was over, it's not. These are my spiders, they're sort of a system that dictates them, you can brush them around, you know, fun, and this is a canvas animation, so I'm just going to, we're almost at the end, I'm just going to briefly go over this, and then there'll be a little interactive demo at the end. So maybe I'll take a sip of water first. So for those of you who don't know, HTML Canvas, you alluded to it also, is a way to draw shapes onto a website in a way that's, like, more similar to how native apps work, or like low level rendering APIs, I don't know.
So what you would do is add a little HTML canvas, and I have it right now just spanning the whole screen, and then I would just, how it works is you create a context from the canvas and then you can just draw to it. So here I'm creating a circle with context.arc and I'm putting it, you know, in this position and it's 500 pixels wide, or maybe that's the radius, and then I'm filling it with black. I can also use context.ellipse to create an ellipse, and here we have a little body of our spider, and then I don't know if you've seen this, but this is how you do the rest of the spider. It's just a bunch of, right, it's like some lines, you can sort of see, there's a big circle there, there's a big circle there, there's a big ellipse here, it blinks, there are some legs, you can figure it out if you would like, or look at the code too.
And then yeah, we can just hook this up with our frame callback, so draw frame, we'll take in our timestamp, and then similar to before, we have a couple steps, we have updating the state and then we have drawing the state or updating the appearance of the webpage, and with a canvas what this means is that we would, you know, maybe we have like a spider object, so we'll set the spider's current position based on whatever, and then we're gonna clear the canvas because we need to draw through it again, and then we'll, you know, draw our spider, whatever, and once we're done with that then we'll request another frame to do it all over again, no rest for the wicked. So here's our spider moving across, I've set it to, essentially the feet will stay still, and then once the legs have stretched a certain amount, right, the legs just sort of snap back over and it sort of looks like it's walking, and if we make it a little smaller and make it move a little faster, then all of a sudden we've got a lovely little friend, as you can see it wiggles, which adds a bit of life and it blinks, you know, nice things, also if you go towards it, it gets a little shy.
So we return, as we started, to the World Wide Web. Our first attempt to make this website better failed, I think, pretty miserably, but maybe we were looking at it wrong, maybe in fact, maybe it's not about all of the flashy language, the pill, the rounded corners, the gradient backgrounds, maybe it's about the friends that we bring along with us, maybe it's about the people that we see these spaces with. Not everything needs to be modern and fancy, as long as we can share it with a friend, perhaps. So why don't we bring our spider along to the World Wide Web? Here I'm just putting a canvas on top of everything and making it not interactable so I can still select the text and I can go to the links and everything.
But our spider's going to come along for a ride. Great. So I'm going to finish this talk with a little demo, maybe I can make this bigger, does that work? Yeah. So now, I was previously on my goofy little slide show, but I'm going now to the real website. I've created a browser extension, I don't have a good name for it, it's just called like, there's a, I mean the pun is really obvious, like spiders on the web, but I can't figure out how to turn it into a good name, so if you've got an idea let me know.
And this extension lets you do two things, one, it lets you bring your own little spider along with you, so you can show it or hide it there. You can also summon, will it come across, there we go, you can add some extra little spiders to come wandering through, and you can also set this to happen randomly. So I currently have this active, I love it, which is, you know, I know, it's good to love your own art, I really, this has made my experience of being alive so much better. Because basically I set, so there's some different settings, the frequency is like how often a spider will come and run across your screen, generational is what I like, which means you'll forget about it, and then if you've been on a website for too long, 10 or 15 minutes later, the spider will just come, like something will come shooting across and you sort of, but it wakes you up. It's good, it's like, I don't smoke, but people who smoke say that it's nice to have an enforced break, or drinking tea, right? It's like a ritual that gets you so that you're not staring at the World Wide Web website for two hours. A spider is going to come through, that's because that's what I do in my free time, a spider is going to come through and break it up a little bit. It's great, so I like that. You can also change the size, so the dinner plate ones are pretty big. There it is, yeah. Lovely. And then also I have some different pixelation sizes, so like right here, zoom in, does it get bigger?
Yeah. Make it crisp. I also kind of like it a little pixelated, I think it looks a little cuter. You can also make it super pixelated, or just like a little blob. I don't know, so, I like this. I think it's nice. I also, the last thing I will say, I put this into a website, so if you don't want to download the browser extension, you can go to spiders.duncanpetrie.com, and I'm actually going to have a QR code, so I would like at least one of you to come and visit me here. I'm using WebSockets for this, so we can hang out together. You can see we have someone, we have another person. And, it's not super polished, but it's fun, so you can see there are five of us here right now. And, can somebody, oh, you're not moving, where are you? I'm gonna, someone come over to the side and then stand still. Yeah, yeah, here we go. Down here, if you approach another spider, little question marks will show up.
And if the spider isn't moving, one of you needs to not move, if the spider isn't moving, yes, yes, here, ah, nope, antsy. If you sit there for long enough, then they start kissing, which I think, this, cause the thing is, right, like, this is a Halloween talk, but I put a lot of work into this and maybe I can also make it a Valentine's Day talk. So, those are all the features. There's also a little info page, so if you, if you go to this website, you can see there's a link to the browser extension, it's currently only on Chromium, but I'll make a Firefox one at some point. And you can also see, like, on my GitHub, the slides are all there, just a plug for me, fonts that I love. And yeah, go fill the web with spiders, thank you very much.