HTML5 : Canvas and Context , code and hack! clear and reset.

In one of our previous tutorials, we have seen how Canvas element is reset. And we also know that its a hack but we can use that to our advantage so as to clear the whole drawing, which was previously drawn through code.
Now, lets see the actual API, which is available to us to clear the whole Context of the Canvas element. The code looks as below.

context.clearRect(topLeftX,topLeftY,width,height);

This actually gives us the ability to clear a rectangular part of the Context of the Canvas. For the whole context to be cleared, just pass on the Canvas width and height as below.

contextRef.clearRect(0,0,canvasRef.width,canvasRef.height);

That simply clears of the drawings from the context. The thing is its the context that is being cleared.
Now lets revisit the hack. the quick hack to clear everything from the Canvas. This is done by setting either height or width of the Canvas element itself. Even if its the same width and same height, but it resets the whole canvas, clears everything form it. So this hack works on Canvas element but the actual code to clear, works on the context of that canvas. The hack code looks as

canvasRef.width=canvasRef.width;
canvasRef.height=canvasRef.height;

If you look at the source code, you can find I have written two different functions to call, one using the actual API and one using the hack. The codes are here for the reference.

//resetting the width and height, it automatically resets the canvas
	//clear the board, quick and dirty, its a HACK!!
	resetCanvas = function (canvasRef){
		canvasRef.width=canvasRef.width;
		canvasRef.height=canvasRef.height;
	};

Now the clear context function is as below.

//clear the board
	resetContext=function(canvasRef,contextRef){
		contextRef.clearRect(0,0,canvasRef.width,canvasRef.height);
	};

Just to enforce the idea one more time, the clear function works on the Context object of the Canvas, while the reset hack works on the Canvas element itself.

Hope that clears the concept.