JS exercises 12 and 13 – Paper.js Mouse Tools

For the next two (brief) exercises, we will run two Paper.js tutorials, so I will point to those resources:

It will be useful to read the whole Creating Mouse Tools chapter, to put the concepts into context.

Still, I will go through the functions to explain some of the main aspects of the code.

Draw lines with mouse exercise (click, drag and release to draw lines)

function onMouseUp(evt){
	var myLine = new Path();
	myLine.strokeColor = "blue";
	myLine.add(evt.downPoint);
	myLine.add(evt.point);
}

Here, the onMouseUp registers the point when we released the mouse button (simply evt.point, where event is any name we give to the function parameter). Paper.js is “smart” enough to keep track of the point where we executed the mouse down that preceded the mouse up (evt.downPoint, where event is any name we give to the function parameter). So, we simply request Paper.js to draw a line from downPoint to point.

Link to the exercise (requires Paper.js): http://mlab.taik.fi/mediacode/coursefiles/course_2011_10/12-draw_lines_mouse.html

Draw blobs (click and drag to draw circles)

function onMouseDrag(event){
	var radius = event.delta.length/2;
	var circle = new Path.Circle(event.middlePoint,radius);
	circle.fillColor = "rgb("+Math.round(Math.random()*255)+",0,0)";
}

Here, a mouse drag event (complete list of tool events can be found here) is used to generate circles. The radius is defined by the delta (difference) of the previous point (lastPoint) where the mouse was when dragging, and the current one. The notion of “previous point” comes from the internal “clock” of Paper.js, which is 60 frames per second by default. So delta compares mouse position at the previous frame to the current one. The length of delta is divided by 2, as we are calculating the radius, not the diameter. The center of the circle is determined by middlePoint – the point between lastPoint and (current) point.

In this exercise we dispensed with the minimum distance (minDistance property) of the original Paperjs.org tutorial. We also used a random color for the circles.

Image from the exercise:

Link to the exercise (requires Paper.js): http://mlab.taik.fi/mediacode/coursefiles/course_2011_10/13-draw_blobs.html

Hopefully these examples will give an idea of how much work a library (and Paper.js in particular) can save us in specific tasks, compared with using basic JavaScript.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s