The Basic Approach
We'll cover the following...
Before we get to the code, let’s talk using English how we are going to make the circle follow our mouse. First, we all know that we need to draw something, and that something will be a circle in our case:
Second, our circle is not going to be loitering around a single location inside our canvas
. Our circle’s position will change based on where exactly our mouse cursor is at any given time. This means that we need to redraw our circle each time the mouse position changes:
You put these two things together, you have the example that you see. Now, as you may have imagined going into this section, this example isn’t a particularly hard one to wrap your head around. That doesn’t mean there is nothing exciting going on behind the scenes, though. When we look at the JavaScript in the next few sections, we’ll touch upon some things that you may not have realized were relevant for this example.
Getting Started
You probably know the drill by now, but the first thing we need is an HTML page with a canvas element ready to run. If you don’t already have a page ready, then put the following into a blank HTML page:
<!DOCTYPE html><html><head><title>Canvas Follow Mouse</title><style>canvas {border: #333 10px solid;}body {padding: 50px;}</style></head><body><canvas id="myCanvas" width="550px" height="350px"></canvas><script>var canvas = document.querySelector("#myCanvas");var context = canvas.getContext("2d");</script></body></html>
If you preview this page in your browser, you’ll notice that there really isn’t much going on here. There is a canvas
element, and this element has the id value of myCanvas. As a timesaver, I provide you with the two lines of code needed to access the canvas
element and its rendering context. If all of this is new to you, take a few moments and review the Getting Started with the Canvas tutorial, for the rest of what you will see will assume you have a basic understanding of how to do things on the canvas
.
Drawing the Circle
The first thing we are going to do is draw our circle. Inside your script
tag, add the following code after ...