Sg2.9
Keyboard Interaction
Index RSS

Scriptographer allows you to interact with the keyboard in two ways: You can either intercept key events and respond to these, or you can check the state of a given key at any moment, to see if it is pressed or not. This tutorial explains both approaches.

Receiving Key Events

To receive information about key presses, define an onKeyDown or onKeyUp handler function in your script.

The following example logs a message to the console whenever the spacebar is pressed and released:

function onKeyDown(event) {
	if(event.keyCode == 'space') {
		console.log('The spacebar was pressed!');
	}
}

function onKeyUp(event) {
	if(event.keyCode == 'space') {
		console.log('The spacebar was released!');
	}
}
Please note:

The onKeyDown event is fired continuously while a key is held down.

Checking Whether a Key is Pressed

To check whether a key is currently being held down, we can use the Key.isDown(key) function.

In the following example we create a path and add segments to it while the user drags the mouse. When the spacebar is pressed while dragging, instead of adding new segments, we move the last segment to the position of the mouse.

var path;
function onMouseDown(event) {
	path = new Path();
	path.add(event.point);
}

function onMouseDrag(event) {
	if(Key.isDown('space')) {
		// If the space key is down, change the point of
		// the last segment to the position of the mouse:
		path.segments.last.point = event.point;
	} else {
		// If the space key is not down, add a segment
		// to the path at the position of the mouse:
		path.add(event.point);
	}
}

Having Fun with the Arrow Keys

The following example creates a path on execution and then adds segment points to it when you press one of the arrow keys in the direction of the key.

// The starting position of the line
var position = new Point(100, 100);

// The amount we will move when an arrow key is pressed:
var step = 5;

var path = new Path();
path.add(position);

function onKeyDown(event) {
	if(event.keyCode == 'left') {
		position.x -= step;
	}

	if(event.keyCode == 'right') {
		position.x += step;
	}
	
	if(event.keyCode == 'up') {
		position.y -= step;
	}
	
	if(event.keyCode == 'down') {
		position.y += step;
	}
	path.add(position);
}