Exercises for Week 2 - Drawing with Canvas
If you're positive that you're not going to use Canvas <i>at all</i> in your game, then you can skip the canvas assignment and work on your main project instead. But you still might want to do the canvas assignments anyway, in order to learn about and try out the capabilities. Up to you.
1. Take your previous assignment, where the player can move a character using the mouse or keyboard (choose one) and modify it so the character is drawn inside a canvas with context.drawImage(). Use the canvas drawing methods to create a background for the character to move around in. This could be a top-down view or a side-view, green hills or outer space or a cityscape or whatever else you want.
Use an object for the character, to encapsulate the x and y position and the image object you're using, like in this example.
You'll need to erase the character each time it moves, so make sure to redraw the part of the background where it just was!
2. Make a canvas with a "game board" background and several "game piece" objects inside it. (You can use image files, or just draw circles or squares). Make it so the player can click on any of these game pieces and drag it around. Listen for mousedown, mousemove, and mouseup events on the canvas -- on a mousedown, check if there's a piece in that location, and if so, begin dragging it. On a mouseup, release any piece that's being dragged. On a mousemove, if there's a piece being dragged, make it move along with the mouse.
Each game piece should be an object; you'll need to have a list containing all the objects. The object should have width and height properties in addition to x and y properties, so that you can write a method to check whether a given mouse location is inside the piece or not. Then you can use that to write a function which takes the x and y coordinates of a mouse click and looks through the list of all objects to find one that matches.