I don't think you should declare the variable and assign the value after. You may change your code similar to the original one:
1. keep the tw and th unchanged
2. use w and h to be the destination width and height of drawImage
3. calculate the x and y with the tw - w and th - h.