function greet() {
return "hello";
}
print(typeof greet);
// gives us a function without a name
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.
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
});
Note that we can access the event created from clicking!
This contains the x and y coordinates of where the click occurred.
<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);
});
}
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>
(Click the link above, then click anywhere in the canvas on the next screen. Arrow right when ready to proceed...)
context.clearRect(0, 0, sketch.offsetWidth, sketch.offsetHeight);
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();
}
(Click the link above, then click anywhere in the canvas on the next screen...)