Click Events

What Will This Code Output in the JavaScript Console?

function greet() {
	return "hello";
}
print(typeof greet);
// gives us a function without a name

Anonymous Functions

We can create functions without names!

function(event) {
		draw_exclamation(event.x, event.y);
}
// gives us a function without a name

…and we can pass these as arguments to another function.

A Click

In addition to detecting when a page loads, you can listen for when an element is clicked:

sketch.addEventListener("click", function(event) {
	// your code here... event.x, event.y
});

Event Objects

Note that we can access the event created from clicking!

This contains the x and y coordinates of where the click occurred.

Clicking Circles (Part #1)

<html>
<head>
    <title></title>
</head>
<body>
<canvas id="sketch" width="800" height="600" style="border: 1px solid gray;">
</canvas>
<script>
document.addEventListener('DOMContentLoaded', main);

var sketch;
var context;

function main() {
	sketch = document.getElementById('sketch');
	context = sketch.getContext("2d");
	context.fillStyle = "#992255";
	sketch.addEventListener("click", function(event) {
		draw_circle(event.x, event.y, 75);
	});
}

Clicking Circles (Part #2)


	function draw_circle(x, y, r) {
		context.beginPath();
		context.arc(x, y, r, 0, 2 * Math.PI, true);
		context.closePath();
		context.fill();
	}
	</script>
	</body>
	</html>

See this example in action!

(Click the link above, then click anywhere in the canvas on the next screen. Arrow right when ready to proceed...)

Clearing the Screen

context.clearRect(0, 0, sketch.offsetWidth, sketch.offsetHeight);

Two Items Relative to One Another #1

document.addEventListener('DOMContentLoaded', main);
var sketch;
var context;
function main() {
	sketch = document.getElementById('sketch');
	context = sketch.getContext("2d");
	sketch.addEventListener("click", function(event) {
		draw_exclamation(event.x, event.y);
	});
}
function draw_exclamation(x, y) {
	context.fillRect(x, y, 50, 100);
	draw_circle(x + 25, y + 150, 25);
}
function draw_circle(x, y, r) {
	context.beginPath();
	context.arc(x, y, r, 0, 2 * Math.PI, true);
	context.closePath();
	context.fill();
}

Two Items Relative to One Another #2

See this example in action!

(Click the link above, then click anywhere in the canvas on the next screen...)