A game is not going to be much fun without some sort of user input. It is time to
introduce Listeners. Listeners are waiting for events to occur, like mouse movement
or a key being pressed on the keyboard. The first thing we need to do is let the
browser know what events we care about. Then we need to indicate what we want to
happen if the event occurs. To do this, we also need to talk about functions. You
can think of functions as a group of commands. The commands can accept some input
and produce a return, although it is optional. When we make a listener for a mouse
event, like a click, it will activate (or call) the function that we specify.
can.addEventListener("click", function(e) { drawRectangle(e); } );
I know this can look scary if you are just starting. Honestly, you can just paste it
in your code and forget about it. Lets talk about the different parts.
<!DOCTYPE HTML>
<html>
<head>
<title>Mouse</title>
</head>
<body style="margin:0px; overflow:hidden;">
<canvas id="canvas"></canvas>
<script>
var can = document.getElementById("canvas");
var ctx = can.getContext('2d');
var cw = can.width = window.innerWidth;
var ch = can.height = window.innerHeight;
ctx.fillStyle = "black";
ctx.fillRect(0, 0, cw, ch);
can.addEventListener("click", function(e) { drawRectangle(e); } );
function drawRectangle(event) {
ctx.fillStyle = "lime";
ctx.fillRect(event.clientX-10, event.clientY-10, 20, 20);
}
</script>
</body>
</html>
The console.log() command is very useful to figure out problems. You can log variables and objects
so that you can see what they contain while the program is running. For example, try putting
"console.log(event);"
into your drawRectangle() function. When you click in the canvas an object will appear in your
console. This object contains all the the properties of that click event which you have access to.
You can use things like the event target to make changes to that target. For example, you could change
the background color of a HTML element when you click on it.
When you have to troubleshoot a problem it can be very useful to put something like mouse coordinates
into the console.log.
console.log("You Clicked at x: "+event.clientX+", y: "+event.clientY);