5
Technical reviewer Matt Inman suggested that the Paper.js developers might have been Photoshop users
familiar with “hand tool,” “direct selection tool,” and so on.
Handling User Input
So far, what we’ve been doing hasn’t had any input from the user. The user can click
on the circles, but it doesn’t do anything. Likewise, trying to drag a circle would have
no effect. Let’s make this a little more interactive, by allowing the user to choose
where the circles get drawn.
It’s important to become comfortable with the asynchronous nature of user input. An
asynchronous event is an event whose timing you don’t have any control over. A user’s
mouse click is an example of an asynchronous event: you can’t be inside your users’
minds, knowing when they’re going to click. Certainly you can prompt their click
response, but it is up to them when—and if—they actually click. Asynchronous
events arising from user input make intuitive sense, but we will cover much less intu‐
itive asynchronous events in later chapters.
Paper.js uses an object called a tool to handle user input. If that choice of names seems
unintuitive to you, you are in good company: I agree, and don’t know why the
Paper.js developers used that terminology.
It might help you to translate “tool” to
“user input tool” in your mind. Let’s replace our code that drew a grid of circles with
the following code:
var
tool
=
new
Tool
();
tool
.
onMouseDown
=
function
(
event
) {
var
c
=
Shape
.
Circle
(
event
.
point
.
x
,
event
.
point
.
y
,
20
);
c
.
fillColor
=
'green'
;
};
The first step in this code is to create our tool object. Once we’ve done that, we can
attach an event handler to it. In this case, the event handler is called
onMouseDown
.
Whenever the user clicks the mouse, the function we’ve attached to this handler is
invoked. This is a very important point to understand. In our previous code, the code
ran right away: we refreshed the browser, and the green circles appeared automati‐
cally. That is not happening here: if it were, it would draw a single green circle some‐
where on the screen. Instead, the code contained between the curly braces after
function
is executed only when the user clicks the mouse on the canvas.
The event handler is doing two things for you: it is executing your code when the
mouse is clicked, and it is telling you where the mouse was clicked. That location is
stored in a property of the argument,
event.point
, which has two properties,
x
and
y
, indicating where the mouse was clicked.
12 | Chapter 1: Your First Application