Week 6

This week, we created a mouse class and learned how to handle the 'mousemove' event. We created another rectangle and set it to follow the mouse. We also learned how to draw text.

The Mouse 'class'

Mouse = function() {
	var mouse = {};
	mouse.x = 0;
	mouse.y = 0;
	function move(e) {
		mouse.x = e.clientX;
		mouse.y = e.clientY;
	canvas.addEventListener('mousemove', move);
	return mouse;

While Mouse() is actually a function, it also functions as a class. Since it returns an object, we can instantiate a mouse object by calling the function. Let's take a look at our use of the class

Using the Mouse class

var mouseRect = new Rectangle(200, 70, 30, 30);
mouse = new Mouse();
//in main()
mouseRect.x = mouse.x;
mouseRect.y = mouse.y;

We created another rectangle and added it to our rectArray so it can be updated and drawn, and created the mouse variable like we might instantiate any other class. Additionally, in our main() function, we set the x and y values of our rectangle to the x and y of the mouse.


//in main()
ctx.fillStyle = "#F33";
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,200);

The code for text is not very complicated. ctx.font sets most parameters for our text, and ctx.fillText() actually draws it. The function takes the string to draw, and the x and y values of the left-most point of the text. Here is the MDN article to the fillText() function. Another function I believe is worth looking at is the measureText() method, which can be found here.