Canvas Part 4

If you’ve played around with the demos, then you might have noticed a little bug. If you click down in one square and let the mouse up in another square, the square you clicked down in will stay green. I haven’t addressed this issue in earlier examples because it’s not actually a bug. What I want to happen, is to allow the user to draw lines.

First, here is the example.

Click and Drag square

Pretty neat eh?

I made the grid larger just to show it could be (plus it looks cooler.) The only real changes to the code happened in the mouse events. We now keep track of the cell the mouse clicked down on, and we bind the onMouseMove function.

var Grid = {
	//Canvas Size
	canvasWidth: 500,
	canvasHeight: 400,
	//Columns and Rows
	numberOfColumns: 50,
	numberOfRows: 50,
	//Size of the cells
	cellWidth:  function() { return this.canvasWidth/this.numberOfColumns; },
	cellHeight: function() { return this.canvasHeight/this.numberOfRows; },

	//Draw the GridLines
	drawGrid: function(display){
		display.beginPath();

		//Draw the Vertical lines
		for(var i=0; i <= this.numberOfColumns; i++){
			//Move to the top of the canvas
			display.moveTo(i*this.cellWidth(), 0)
			//Draw the line
			display.lineTo( i*this.cellWidth(), this.canvasHeight );
		}

		//Draw the Horizontal lines.
		for(var i=0; i <= this.numberOfRows; i++){
			//Move to the left of the canvas
			display.moveTo(0, i*this.cellHeight())
			//Draw the line
			display.lineTo( this.canvasWidth, i*this.cellHeight() );
		}

		display.stroke();
	},

	//Find which cell was clicked.
	cellMouseIn: function(evt, offset){
		//Create an Object to hold the column/row
		var position = {
			column: -1,
			row: -1,
		};

		//Find the poistion of the mouse
		var x_pos = Math.floor(evt.pageX - offset.left);
		var y_pos = Math.floor(evt.pageY - offset.top);

		//Now which column was it clicked?
		for(var column=0; column < this.numberOfColumns; column++){
			//Find the column
			if( x_pos >= column*this.cellWidth() && x_pos <= (column+1)*this.cellWidth() ){
				//Found it!
				position.column = column;
				//Fow find the row
				for(var row=0; row < this.numberOfRows; row++){
					//Find the row
					if( y_pos >= row*this.cellHeight() && y_pos <= (row+1)*this.cellHeight()){
						//Found it!
						position.row = row;
					}
				} //End Row
			}
		} // End Column

		//Return the found position
		return position;
	},
	//(re)Draw a cell at the position.
	drawCell: function(display, position){
		var y_pos = position.row * this.cellHeight();
		var x_pos = position.column * this.cellWidth();

		//Draw the cell
		display.fillRect( x_pos, y_pos, this.cellWidth(), this.cellHeight());
		//ReDraw the grid
		this.drawGrid(display);
	},
};

var display;		//This is going to be our Drawing Context

$(document).ready(function(){
	//Setup the Canvas
	$("#display").attr({
		width: Grid.canvasWidth,
		height: Grid.canvasHeight,
	}) 	/* Register Events */
		.bind("mousedown", onMouseDown)
		.bind("mouseup", onMouseUp);

	//Get the context
	display = $("#display")[0].getContext("2d");

	//Draw it
	draw();

});

//Called when the mouse is down in a cell
function onMouseDown(evt){
	//Save the cell That the mouse is in
	downSquare = Grid.cellMouseIn(evt, $("#display").offset() );

	//Start drawing on mouse move
	$("#display").bind("mousemove", onMouseMove);
}
//Called when the mouse is up in  a cell
function onMouseUp(evt){
	//Remove the mousemove
	$("#display").unbind("mousemove", onMouseMove);
}
//Called when the mouse moves on the canvas
function onMouseMove(evt){
	//Blank the grid
	draw();

	//Get the current square position
	var currentPos = Grid.cellMouseIn(evt, $("#display").offset() );

	//Change the Squares Color.
	display.fillStyle = "#0F0";
	//Color the downSquare
	Grid.drawCell(display, downSquare);
	//Color the cell we are on
	Grid.drawCell(display, currentPos);

	//Get the length of the line
	var line_length = Math.sqrt( Math.pow( downSquare.column - currentPos.column, 2) + Math.pow(downSquare.row - currentPos.row, 2));
	//Now draw each point
	for(var i=0; i < line_length; i++){
		//Get the Row/Column of the cell to color
		var cell = {};
		cell.column = Math.round( downSquare.column+(currentPos.column-downSquare.column)*i/line_length);
		cell.row = Math.round( downSquare.row+(currentPos.row-downSquare.row)*i/line_length);

		//Now redraw it
		Grid.drawCell(display, cell);
	}

}

//Draw on the Canvas
function draw(){
	//Lets draw the outline of four squares on a black canvas.

	//Draw the background
	display.fillStyle = "#FFF";
	display.fillRect(0,0, Grid.canvasWidth, Grid.canvasHeight);

	//draw grid lines
	display.strokeStyle = "#ccc";
	display.lineWidth = 2;
	//Tell the Grid to draw
	Grid.drawGrid(display);
}
Share

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

1 Comment »

 
  • I beloved as much as you will receive performed proper here. The caricature is tasteful, your authored subject matter stylish. nevertheless, you command get bought an shakiness over that you wish be delivering the following. sick unquestionably come further beforehand once more since precisely the same nearly a lot regularly within case you defend this hike.

 

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv Enabled