check this script:
http://jsfiddle.net/U8BE5/1/
It should give you some ideas on how to handle your boundary conditions (also with scaling).
I'm not sure why you chose to use two canvases and don't use jQuery, this probably does more harm than good.
Corresponding code for borders:
if (gX > 0) gX = 0; if (gX < canvas.width - gW * gScale) gX = canvas.width - gW * gScale; if (gY > 0) gY = 0; if (gY < canvas.height - gH * gScale) gY = canvas.height - gH * gScale;
Check out my general approach in the script to see if you want to switch your strategy a bit.
To be honest, I could not execute some of your codes.
source share